AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/11/24 16:16 flow patch-triage
38m Args:
null

Results:
{
  "EnableConfigs": [
    "ROOTNS",
    "NAMESPACES",
    "USER_NS",
    "PID_NS",
    "UTS_NS",
    "IPC_NS",
    "NET_NS",
    "CGROUPS",
    "TIME_NS",
    "POSIX_MQUEUE",
    "PROC_FS",
    "SECURITY"
  ],
  "FocusSymbols": [
    "sys_rootns",
    "__x64_sys_rootns",
    "rootns_ioctl",
    "rootns_prepare_fork",
    "rootns_finish_fork",
    "copy_rootns",
    "exit_rootns",
    "fsconfig_set_rootns",
    "move_mount_mntns",
    "mnt_ns_get_root",
    "nsproxy_open_namespace",
    "proc_set_rootns",
    "mqueue_set_rootns"
  ],
  "KMSANReasoning": "The patch series introduces the root namespace (`rootns`) facility, adding the `sys_rootns` syscall, `CLONE_INTO_ROOTNS` support in `clone3()`, `FSCONFIG_SET_ROOTNS` in `fsconfig()`, `MOVE_MOUNT_T_MNTNS` in `move_mount()`, and control ioctls (`ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`).\n\nKMSAN vs. KASAN analysis:\n- Potential bug risks in this patch: The patch modifies namespace reference counting (`mnt_ns`, `pid_ns`, `user_ns`, `nsproxy`), task credentials, mount hierarchy manipulation, and synchronization under locks (`tasklist_lock`, `rootns-\u003elock`, waitqueues). These represent risks of refcount leaks, use-after-free, double free, locking deadlocks, or capability bypasses—all of which are covered by standard KASAN, LOCKDEP, and standard kernel bug detectors.\n- Uninitialized memory / info-leak analysis (KMSAN):\n  1. Heap allocations: `struct rootns` is allocated with `kzalloc_obj()`, its LSM security blob is allocated with `kzalloc()` via `lsm_blob_alloc()`, and namespace structures use zeroed slab allocations (`kmem_cache_zalloc()`).\n  2. Stack variables: Stack paths (`struct path from_path`, `to_path`, `root`) use `= {}` zero-initialization with `__free()` cleanup helpers.\n  3. Kernel-to-user copies: The only user-facing structure copied to userspace is `struct rootns_wait_args` in `rootns_wait()`. It contains two 32-bit fields (`__u32 flags` at offset 0 and `__s32 status` at offset 4) totaling 8 bytes, with no internal or trailing padding bytes on either 32-bit or 64-bit architectures. It is read via `copy_from_user()`, `status` is overwritten, and written back via `copy_to_user()`, leaving zero chance of uninitialized data exposure.\n  4. User input handling: `copy_clone_args_from_user()` uses `copy_struct_from_user()`, which automatically zeroes trailing fields when older or smaller structs are passed.\n\nBecause no uninitialized memory risks or kernel info-leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted. Standard KASAN fuzzing is sufficient.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch introduces the root namespace (CONFIG_ROOTNS) subsystem, providing a new rootns() syscall, new ioctls (ROOTNS_GET_NSFD, ROOTNS_WAIT, ROOTNS_KILL), a new clone3 flag (CLONE_INTO_ROOTNS), fsconfig commands (FSCONFIG_SET_ROOTNS), and move_mount operations (MOVE_MOUNT_T_MNTNS). These modify core namespace, fork, VFS, and security subsystem logic that is directly reachable from userspace in standard virtualized environments. Fuzzing is highly warranted to test complex lifecycle transitions, concurrency, and security invariants.",
  "WorthFuzzing": true
}

1/1 2026/11/24 16:16 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 5eee798c49d5a9e72c751aa7953598064d617c03\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Tue Nov 24 16:16:22 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst\nindex a68b1bea57a85c..56d0ac4eb0879a 100644\n--- a/Documentation/userspace-api/index.rst\n+++ b/Documentation/userspace-api/index.rst\n@@ -17,6 +17,7 @@ System calls\n    :maxdepth: 1\n \n    unshare\n+   rootns\n    futex2\n    ebpf/index\n    ioctl/index\ndiff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst\nindex dbe46204099996..d8dc926ea28303 100644\n--- a/Documentation/userspace-api/ioctl/ioctl-number.rst\n+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst\n@@ -385,6 +385,7 @@ Code  Seq#    Include File                                             Comments\n 0xB8  01-02  uapi/misc/mrvl_cn10k_dpi.h                                Marvell CN10K DPI driver\n 0xB8  all    uapi/linux/mshv.h                                         Microsoft Hyper-V /dev/mshv driver\n                                                                        \u003cmailto:linux-hyperv@vger.kernel.org\u003e\n+0xB9  00-0F  uapi/linux/rootns.h                                       Root namespace uAPI\n 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin\n                                                                        \u003cmailto:pasha.tatashin@soleen.com\u003e\n 0xC0  00-0F  linux/usb/iowarrior.h\ndiff --git a/Documentation/userspace-api/rootns.rst b/Documentation/userspace-api/rootns.rst\nnew file mode 100644\nindex 00000000000000..5326fd2eeb2123\n--- /dev/null\n+++ b/Documentation/userspace-api/rootns.rst\n@@ -0,0 +1,56 @@\n+.. SPDX-License-Identifier: GPL-2.0\n+\n+===================\n+Root namespace uAPI\n+===================\n+\n+Overview\n+========\n+\n+.. kernel-doc:: kernel/rootns.c\n+   :doc: Overview\n+\n+Flags\n+=====\n+\n+.. kernel-doc:: include/uapi/linux/rootns.h\n+   :identifiers: rootns_flags\n+\n+Ioctls\n+======\n+\n+.. kernel-doc:: include/uapi/linux/rootns.h\n+   :doc: ROOTNS_GET_NSFD\n+\n+.. kernel-doc:: include/uapi/linux/rootns.h\n+   :identifiers: rootns_wait_args\n+\n+.. kernel-doc:: include/uapi/linux/rootns.h\n+   :doc: ROOTNS_WAIT\n+\n+.. kernel-doc:: include/uapi/linux/rootns.h\n+   :doc: ROOTNS_KILL\n+\n+System calls\n+============\n+\n+.. kernel-doc:: kernel/rootns.c\n+   :identifiers: sys_rootns\n+\n+Process creation\n+================\n+\n+.. kernel-doc:: kernel/rootns.c\n+   :doc: CLONE_INTO_ROOTNS\n+\n+Filesystem configuration\n+========================\n+\n+.. kernel-doc:: fs/fsopen.c\n+   :doc: FSCONFIG_SET_ROOTNS\n+\n+Mount tree installation\n+=======================\n+\n+.. kernel-doc:: fs/namespace.c\n+   :doc: MOVE_MOUNT_T_MNTNS\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 8fd9991739547c..a24d0b16f42f42 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -24511,6 +24511,17 @@ F:\tinclude/linux/mfd/rohm-bd96802.h\n F:\tinclude/linux/mfd/rohm-generic.h\n F:\tinclude/linux/mfd/rohm-shared.h\n \n+ROOT NAMESPACE\n+M:\tDavid Howells \u003cdhowells@redhat.com\u003e\n+M:\tJarkko Sakkinen \u003cjarkko@kernel.org\u003e\n+L:\tlinux-fsdevel@vger.kernel.org\n+S:\tMaintained\n+F:\tDocumentation/userspace-api/rootns.rst\n+F:\tinclude/linux/rootns.h\n+F:\tinclude/uapi/linux/rootns.h\n+F:\tkernel/rootns.c\n+F:\ttools/testing/selftests/rootns/\n+\n ROTATION DRIVER FOR ALLWINNER A83T\n M:\tJernej Skrabec \u003cjernej.skrabec@gmail.com\u003e\n L:\tlinux-media@vger.kernel.org\ndiff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl\nindex 52e3538cc7df41..ea790cceb67acf 100644\n--- a/arch/alpha/kernel/syscalls/syscall.tbl\n+++ b/arch/alpha/kernel/syscalls/syscall.tbl\n@@ -512,3 +512,4 @@\n 580\tcommon\tlistns\t\t\t\tsys_listns\n 581\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 582\tcommon\tfchroot\t\t\t\tsys_fchroot\n+583\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/arm/tools/syscall.tbl b/arch/arm/tools/syscall.tbl\nindex 55717ed32c27e6..531b2a2dce72d1 100644\n--- a/arch/arm/tools/syscall.tbl\n+++ b/arch/arm/tools/syscall.tbl\n@@ -487,3 +487,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/arm64/tools/syscall_32.tbl b/arch/arm64/tools/syscall_32.tbl\nindex df2d1d82fb3ccf..8ef224c0dd42b6 100644\n--- a/arch/arm64/tools/syscall_32.tbl\n+++ b/arch/arm64/tools/syscall_32.tbl\n@@ -484,3 +484,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/m68k/kernel/syscalls/syscall.tbl b/arch/m68k/kernel/syscalls/syscall.tbl\nindex ba7a4d8903d044..77239262dc26f5 100644\n--- a/arch/m68k/kernel/syscalls/syscall.tbl\n+++ b/arch/m68k/kernel/syscalls/syscall.tbl\n@@ -472,3 +472,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/microblaze/kernel/syscalls/syscall.tbl b/arch/microblaze/kernel/syscalls/syscall.tbl\nindex 76d7cbe2a133c4..df53332ce4a5b7 100644\n--- a/arch/microblaze/kernel/syscalls/syscall.tbl\n+++ b/arch/microblaze/kernel/syscalls/syscall.tbl\n@@ -478,3 +478,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/mips/kernel/syscalls/syscall_n32.tbl b/arch/mips/kernel/syscalls/syscall_n32.tbl\nindex 9ae88e4eac61ee..84db40158bf0b3 100644\n--- a/arch/mips/kernel/syscalls/syscall_n32.tbl\n+++ b/arch/mips/kernel/syscalls/syscall_n32.tbl\n@@ -411,3 +411,4 @@\n 470\tn32\tlistns\t\t\t\tsys_listns\n 471\tn32\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tn32\tfchroot\t\t\t\tsys_fchroot\n+473\tn32\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/mips/kernel/syscalls/syscall_n64.tbl b/arch/mips/kernel/syscalls/syscall_n64.tbl\nindex 83dc93a0712f12..9e874a95850300 100644\n--- a/arch/mips/kernel/syscalls/syscall_n64.tbl\n+++ b/arch/mips/kernel/syscalls/syscall_n64.tbl\n@@ -387,3 +387,4 @@\n 470\tn64\tlistns\t\t\t\tsys_listns\n 471\tn64\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tn64\tfchroot\t\t\t\tsys_fchroot\n+473\tn64\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/mips/kernel/syscalls/syscall_o32.tbl b/arch/mips/kernel/syscalls/syscall_o32.tbl\nindex 9c62429c9b7b4e..592c2225f4ce36 100644\n--- a/arch/mips/kernel/syscalls/syscall_o32.tbl\n+++ b/arch/mips/kernel/syscalls/syscall_o32.tbl\n@@ -460,3 +460,4 @@\n 470\to32\tlistns\t\t\t\tsys_listns\n 471\to32\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\to32\tfchroot\t\t\t\tsys_fchroot\n+473\to32\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/parisc/kernel/syscalls/syscall.tbl b/arch/parisc/kernel/syscalls/syscall.tbl\nindex 88adc4016cce01..93f8539bd1795d 100644\n--- a/arch/parisc/kernel/syscalls/syscall.tbl\n+++ b/arch/parisc/kernel/syscalls/syscall.tbl\n@@ -471,3 +471,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/powerpc/kernel/syscalls/syscall.tbl b/arch/powerpc/kernel/syscalls/syscall.tbl\nindex cfbb70039ff007..7e12f74a27c1b4 100644\n--- a/arch/powerpc/kernel/syscalls/syscall.tbl\n+++ b/arch/powerpc/kernel/syscalls/syscall.tbl\n@@ -563,3 +563,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tnospu\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tnospu\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/s390/kernel/syscalls/syscall.tbl b/arch/s390/kernel/syscalls/syscall.tbl\nindex 1b45e68a217bb0..ab303fbb86f380 100644\n--- a/arch/s390/kernel/syscalls/syscall.tbl\n+++ b/arch/s390/kernel/syscalls/syscall.tbl\n@@ -399,3 +399,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/sh/kernel/syscalls/syscall.tbl b/arch/sh/kernel/syscalls/syscall.tbl\nindex ace068dff0de03..e92778075bcb48 100644\n--- a/arch/sh/kernel/syscalls/syscall.tbl\n+++ b/arch/sh/kernel/syscalls/syscall.tbl\n@@ -476,3 +476,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/sparc/kernel/syscalls/syscall.tbl b/arch/sparc/kernel/syscalls/syscall.tbl\nindex 5b9fe0e8140f26..20d6c572d3f153 100644\n--- a/arch/sparc/kernel/syscalls/syscall.tbl\n+++ b/arch/sparc/kernel/syscalls/syscall.tbl\n@@ -518,3 +518,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl\nindex 2c172ef48dfd33..98cb11b717e5ca 100644\n--- a/arch/x86/entry/syscalls/syscall_32.tbl\n+++ b/arch/x86/entry/syscalls/syscall_32.tbl\n@@ -478,3 +478,4 @@\n 470\ti386\tlistns\t\t\tsys_listns\n 471\ti386\trseq_slice_yield\tsys_rseq_slice_yield\n 472\ti386\tfchroot\t\t\tsys_fchroot\n+473\ti386\trootns\t\t\tsys_rootns\ndiff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl\nindex d5b6045b0090cc..674fa2b4b23878 100644\n--- a/arch/x86/entry/syscalls/syscall_64.tbl\n+++ b/arch/x86/entry/syscalls/syscall_64.tbl\n@@ -397,6 +397,7 @@\n 470\tcommon\tlistns\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\tsys_rootns\n \n #\n # Due to a historical design error, certain syscalls are numbered differently\ndiff --git a/arch/xtensa/kernel/syscalls/syscall.tbl b/arch/xtensa/kernel/syscalls/syscall.tbl\nindex d354bb231796c2..82b7344a099cb3 100644\n--- a/arch/xtensa/kernel/syscalls/syscall.tbl\n+++ b/arch/xtensa/kernel/syscalls/syscall.tbl\n@@ -443,3 +443,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/fs/devpts/inode.c b/fs/devpts/inode.c\nindex bd1e8eb26edb70..db5a5c7a07db01 100644\n--- a/fs/devpts/inode.c\n+++ b/fs/devpts/inode.c\n@@ -434,6 +434,8 @@ static int devpts_init_fs_context(struct fs_context *fc)\n \tfsi-\u003emount_opts.max     = NR_UNIX98_PTY_MAX;\n \n \tif (fc-\u003epurpose == FS_CONTEXT_FOR_MOUNT \u0026\u0026\n+\t    !fc-\u003erootns_bound \u0026\u0026\n+\t    fc-\u003euser_ns == \u0026init_user_ns \u0026\u0026\n \t    current-\u003ensproxy-\u003emnt_ns == init_task.nsproxy-\u003emnt_ns)\n \t\tfsi-\u003emount_opts.reserve = true;\n \ndiff --git a/fs/filesystems.c b/fs/filesystems.c\nindex 3083d904df9bc6..9429844bf6bf9d 100644\n--- a/fs/filesystems.c\n+++ b/fs/filesystems.c\n@@ -18,6 +18,7 @@\n #include \u003clinux/uaccess.h\u003e\n #include \u003clinux/fs_parser.h\u003e\n #include \u003clinux/rculist.h\u003e\n+#include \"internal.h\"\n \n /*\n  * Read-mostly filesystem drivers list.\n@@ -390,6 +391,20 @@ static struct file_system_type *__get_fs_type(const char *name, int len)\n \treturn fs;\n }\n \n+struct file_system_type *get_fs_type_noload(const char *name)\n+{\n+\tstruct file_system_type *fs;\n+\tconst char *dot = strchr(name, '.');\n+\tint len = dot ? dot - name : strlen(name);\n+\n+\tfs = __get_fs_type(name, len);\n+\tif (dot \u0026\u0026 fs \u0026\u0026 !(fs-\u003efs_flags \u0026 FS_HAS_SUBTYPE)) {\n+\t\tput_filesystem(fs);\n+\t\tfs = NULL;\n+\t}\n+\treturn fs;\n+}\n+\n struct file_system_type *get_fs_type(const char *name)\n {\n \tstruct file_system_type *fs;\ndiff --git a/fs/fs_context.c b/fs/fs_context.c\nindex a50584df97bea7..cd004750b99c5b 100644\n--- a/fs/fs_context.c\n+++ b/fs/fs_context.c\n@@ -249,6 +249,7 @@ EXPORT_SYMBOL(generic_parse_monolithic);\n  * @sb_flags: Filesystem/superblock flags (SB_*)\n  * @sb_flags_mask: Applicable members of @sb_flags\n  * @purpose: The purpose that this configuration shall be used for.\n+ * @init: Whether to initialise the filesystem context immediately.\n  *\n  * Open a filesystem and create a mount context.  The mount context is\n  * initialised with the supplied flags and, if a submount/automount from\n@@ -259,7 +260,8 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,\n \t\t\t\t      struct dentry *reference,\n \t\t\t\t      unsigned int sb_flags,\n \t\t\t\t      unsigned int sb_flags_mask,\n-\t\t\t\t      enum fs_context_purpose purpose)\n+\t\t\t\t      enum fs_context_purpose purpose,\n+\t\t\t\t      bool init)\n {\n \tstruct fs_context *fc;\n \tint ret = -ENOMEM;\n@@ -292,6 +294,9 @@ static struct fs_context *alloc_fs_context(struct file_system_type *fs_type,\n \t\tbreak;\n \t}\n \n+\tif (!init)\n+\t\treturn fc;\n+\n \tret = fc-\u003efs_type-\u003einit_fs_context(fc);\n \tif (ret \u003c 0)\n \t\tgoto err_fc;\n@@ -307,10 +312,16 @@ struct fs_context *fs_context_for_mount(struct file_system_type *fs_type,\n \t\t\t\t\tunsigned int sb_flags)\n {\n \treturn alloc_fs_context(fs_type, NULL, sb_flags, 0,\n-\t\t\t\t\tFS_CONTEXT_FOR_MOUNT);\n+\t\t\t\tFS_CONTEXT_FOR_MOUNT, true);\n }\n EXPORT_SYMBOL(fs_context_for_mount);\n \n+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type)\n+{\n+\treturn alloc_fs_context(fs_type, NULL, 0, 0,\n+\t\t\t\tFS_CONTEXT_FOR_MOUNT, false);\n+}\n+\n struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,\n \t\t\t\t\tunsigned int sb_flags,\n \t\t\t\t\tunsigned int sb_flags_mask)\n@@ -320,7 +331,8 @@ struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,\n \t\treturn ERR_PTR(-EINVAL);\n \n \treturn alloc_fs_context(dentry-\u003ed_sb-\u003es_type, dentry, sb_flags,\n-\t\t\t\tsb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE);\n+\t\t\t\tsb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE,\n+\t\t\t\ttrue);\n }\n \n /**\n@@ -337,7 +349,8 @@ struct fs_context *fs_context_for_submount(struct file_system_type *type,\n \tstruct fs_context *fc;\n \tint ret;\n \n-\tfc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT);\n+\tfc = alloc_fs_context(type, reference, 0, 0, FS_CONTEXT_FOR_SUBMOUNT,\n+\t\t\t      true);\n \tif (IS_ERR(fc))\n \t\treturn fc;\n \ndiff --git a/fs/fsopen.c b/fs/fsopen.c\nindex 70024870fefa2e..85b31af68a4d65 100644\n--- a/fs/fsopen.c\n+++ b/fs/fsopen.c\n@@ -13,9 +13,14 @@\n #include \u003clinux/security.h\u003e\n #include \u003clinux/anon_inodes.h\u003e\n #include \u003clinux/namei.h\u003e\n+#include \u003clinux/capability.h\u003e\n+#include \u003clinux/nsproxy.h\u003e\n+#include \u003clinux/rootns.h\u003e\n+#include \u003clinux/user_namespace.h\u003e\n #include \u003clinux/file.h\u003e\n #include \u003cuapi/linux/mount.h\u003e\n #include \u003clinux/audit.h\u003e\n+#include \u003cnet/net_namespace.h\u003e\n #include \"internal.h\"\n #include \"mount.h\"\n \n@@ -41,6 +46,94 @@ static inline const char *fetch_message_locked(struct fc_log *log, size_t len,\n \treturn p;\n }\n \n+/**\n+ * DOC: FSCONFIG_SET_ROOTNS\n+ *\n+ * ``fsconfig(fsfd, FSCONFIG_SET_ROOTNS, NULL, NULL, rootnsfd)`` binds a newly\n+ * opened filesystem context to ``rootnsfd`` once before any parameters are\n+ * supplied (subsequent calls fail with ``-EBUSY``).\n+ *\n+ * The caller must hold ``CAP_SYS_ADMIN`` in the target ``rootns`` user\n+ * namespace, allowing unprivileged callers to configure ``FS_USERNS_MOUNT``\n+ * filesystems without entering the user namespace first.\n+ *\n+ * The context is initialized against the ``rootns`` network namespace,\n+ * ``fc-\u003euser_ns`` is delegated to the ``rootns`` user namespace for\n+ * ``FS_USERNS_MOUNT`` and ``FS_USERNS_DELEGATABLE`` filesystems when the\n+ * mounter ``fsuid``/``fsgid`` map into it or the caller lacks\n+ * ``CAP_SYS_ADMIN`` in its own user namespace, and ``proc`` and ``mqueue``\n+ * contexts bind to the target ``rootns`` PID and IPC namespaces.\n+ */\n+static int fsconfig_set_rootns(struct fs_context *fc, struct fs_parameter *param)\n+{\n+\tstruct user_namespace *user_ns;\n+\tstruct rootns *c;\n+\tint ret;\n+\n+\tif (!is_rootns_file(param-\u003efile))\n+\t\treturn -EINVAL;\n+\n+\tc = param-\u003efile-\u003eprivate_data;\n+\tuser_ns = c-\u003euser_ns;\n+\tif (!ns_capable(user_ns, CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\tif (fc-\u003eneed_free \u0026\u0026 fc-\u003eops \u0026\u0026 fc-\u003eops-\u003efree)\n+\t\tfc-\u003eops-\u003efree(fc);\n+\tfc-\u003eneed_free = false;\n+\tfc-\u003efs_private = NULL;\n+\tfc-\u003es_fs_info = NULL;\n+\tfc-\u003eops = NULL;\n+\tfc-\u003esb_flags = 0;\n+\tfc-\u003eglobal = false;\n+\tsecurity_free_mnt_opts(\u0026fc-\u003esecurity);\n+\n+\tif (fc-\u003elog.prefix \u0026\u0026 strcmp(fc-\u003efs_type-\u003ename, fc-\u003elog.prefix)) {\n+\t\tstruct file_system_type *orig;\n+\n+\t\torig = get_fs_type_noload(fc-\u003elog.prefix);\n+\t\tif (!orig) {\n+\t\t\tfc-\u003ephase = FS_CONTEXT_FAILED;\n+\t\t\treturn -ENODEV;\n+\t\t}\n+\t\tput_filesystem(fc-\u003efs_type);\n+\t\tfc-\u003efs_type = orig;\n+\t}\n+\n+\tput_net(fc-\u003enet_ns);\n+\tfc-\u003enet_ns = get_net(c-\u003ens-\u003enet_ns);\n+\tput_user_ns(fc-\u003euser_ns);\n+\tif ((fc-\u003efs_type-\u003efs_flags \u0026 (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE)) \u0026\u0026\n+\t    ((kuid_has_mapping(user_ns, fc-\u003ecred-\u003efsuid) \u0026\u0026\n+\t      kgid_has_mapping(user_ns, fc-\u003ecred-\u003efsgid)) ||\n+\t     !ns_capable(fc-\u003ecred-\u003euser_ns, CAP_SYS_ADMIN)))\n+\t\tfc-\u003euser_ns = get_user_ns(user_ns);\n+\telse\n+\t\tfc-\u003euser_ns = get_user_ns(fc-\u003ecred-\u003euser_ns);\n+\n+\tfc-\u003erootns_bound = true;\n+\tfc-\u003erootns_mnt_id = c-\u003ens-\u003emnt_ns-\u003ens.ns_id;\n+\n+\tret = fc-\u003efs_type-\u003einit_fs_context(fc);\n+\tif (ret \u003c 0) {\n+\t\tfc-\u003erootns_bound = false;\n+\t\tfc-\u003ephase = FS_CONTEXT_FAILED;\n+\t\treturn ret;\n+\t}\n+\tfc-\u003eneed_free = true;\n+\n+\tif (fc-\u003eops-\u003eset_rootns) {\n+\t\tret = fc-\u003eops-\u003eset_rootns(fc, c);\n+\t\tif (ret \u003c 0) {\n+\t\t\tfc-\u003erootns_bound = false;\n+\t\t\tfc-\u003ephase = FS_CONTEXT_FAILED;\n+\t\t\treturn ret;\n+\t\t}\n+\t}\n+\tfc-\u003ephase = FS_CONTEXT_CREATE_PARAMS;\n+\treturn 0;\n+}\n+\n /*\n  * Allow the user to read back any error, warning or informational messages.\n  * Only one message is returned for each read(2) call.\n@@ -123,9 +216,11 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)\n \tstruct file_system_type *fs_type;\n \tstruct fs_context *fc;\n \tconst char *fs_name;\n+\tbool priv;\n \tint ret;\n \n-\tif (!may_mount())\n+\tpriv = may_mount();\n+\tif (!priv \u0026\u0026 !IS_ENABLED(CONFIG_ROOTNS))\n \t\treturn -EPERM;\n \n \tif (flags \u0026 ~FSOPEN_CLOEXEC)\n@@ -137,17 +232,23 @@ SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)\n \n \taudit_log_fsopen(fs_name);\n \n-\tfs_type = get_fs_type(fs_name);\n+\tfs_type = priv ? get_fs_type(fs_name) : get_fs_type_noload(fs_name);\n \tkfree(fs_name);\n \tif (!fs_type)\n-\t\treturn -ENODEV;\n+\t\treturn priv ? -ENODEV : -EPERM;\n \n-\tfc = fs_context_for_mount(fs_type, 0);\n+\tif (!priv \u0026\u0026 !(fs_type-\u003efs_flags \u0026 FS_USERNS_MOUNT)) {\n+\t\tput_filesystem(fs_type);\n+\t\treturn -EPERM;\n+\t}\n+\n+\tfc = priv ? fs_context_for_mount(fs_type, 0) :\n+\t\t    fs_context_for_unpriv_mount(fs_type);\n \tput_filesystem(fs_type);\n \tif (IS_ERR(fc))\n \t\treturn PTR_ERR(fc);\n \n-\tfc-\u003ephase = FS_CONTEXT_CREATE_PARAMS;\n+\tfc-\u003ephase = priv ? FS_CONTEXT_CREATE_NS : FS_CONTEXT_AWAITING_NS;\n \n \tret = fscontext_alloc_log(fc);\n \tif (ret \u003c 0)\n@@ -222,7 +323,8 @@ static int vfs_cmd_create(struct fs_context *fc, bool exclusive)\n \tstruct super_block *sb;\n \tint ret;\n \n-\tif (fc-\u003ephase != FS_CONTEXT_CREATE_PARAMS)\n+\tif (fc-\u003ephase != FS_CONTEXT_CREATE_NS \u0026\u0026\n+\t    fc-\u003ephase != FS_CONTEXT_CREATE_PARAMS)\n \t\treturn -EBUSY;\n \n \tif (!mount_capable(fc))\n@@ -291,6 +393,8 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,\n \tret = finish_clean_context(fc);\n \tif (ret)\n \t\treturn ret;\n+\tif (fc-\u003ephase == FS_CONTEXT_AWAITING_NS \u0026\u0026 cmd != FSCONFIG_SET_ROOTNS)\n+\t\treturn -EPERM;\n \tswitch (cmd) {\n \tcase FSCONFIG_CMD_CREATE:\n \t\treturn vfs_cmd_create(fc, false);\n@@ -298,9 +402,17 @@ static int vfs_fsconfig_locked(struct fs_context *fc, int cmd,\n \t\treturn vfs_cmd_create(fc, true);\n \tcase FSCONFIG_CMD_RECONFIGURE:\n \t\treturn vfs_cmd_reconfigure(fc);\n+\tcase FSCONFIG_SET_ROOTNS:\n+\t\tif (fc-\u003ephase != FS_CONTEXT_AWAITING_NS \u0026\u0026\n+\t\t    fc-\u003ephase != FS_CONTEXT_CREATE_NS)\n+\t\t\treturn -EBUSY;\n+\t\treturn fsconfig_set_rootns(fc, param);\n+\n \tdefault:\n-\t\tif (fc-\u003ephase != FS_CONTEXT_CREATE_PARAMS \u0026\u0026\n-\t\t    fc-\u003ephase != FS_CONTEXT_RECONF_PARAMS)\n+\t\tif (fc-\u003ephase == FS_CONTEXT_CREATE_NS)\n+\t\t\tfc-\u003ephase = FS_CONTEXT_CREATE_PARAMS;\n+\t\telse if (fc-\u003ephase != FS_CONTEXT_CREATE_PARAMS \u0026\u0026\n+\t\t\t fc-\u003ephase != FS_CONTEXT_RECONF_PARAMS)\n \t\t\treturn -EBUSY;\n \n \t\treturn vfs_parse_fs_param(fc, param);\n@@ -390,6 +502,10 @@ SYSCALL_DEFINE5(fsconfig,\n \t\tif (!_key || _value || aux \u003c 0)\n \t\t\treturn -EINVAL;\n \t\tbreak;\n+\tcase FSCONFIG_SET_ROOTNS:\n+\t\tif (_key || _value || aux \u003c 0)\n+\t\t\treturn -EINVAL;\n+\t\tbreak;\n \tcase FSCONFIG_CMD_CREATE:\n \tcase FSCONFIG_CMD_CREATE_EXCL:\n \tcase FSCONFIG_CMD_RECONFIGURE:\n@@ -457,6 +573,12 @@ SYSCALL_DEFINE5(fsconfig,\n \t\t\tgoto out_key;\n \t\tparam.dirfd = aux;\n \t\tbreak;\n+\tcase FSCONFIG_SET_ROOTNS:\n+\t\tret = -EBADF;\n+\t\tparam.file = fget(aux);\n+\t\tif (!param.file)\n+\t\t\tgoto out_key;\n+\t\tbreak;\n \tdefault:\n \t\tbreak;\n \t}\n@@ -482,6 +604,7 @@ SYSCALL_DEFINE5(fsconfig,\n \t\t\tputname(param.name);\n \t\tbreak;\n \tcase FSCONFIG_SET_FD:\n+\tcase FSCONFIG_SET_ROOTNS:\n \t\tif (param.file)\n \t\t\tfput(param.file);\n \t\tbreak;\ndiff --git a/fs/internal.h b/fs/internal.h\nindex 3f2fbac40f8ee5..d6815bf6ea9bb7 100644\n--- a/fs/internal.h\n+++ b/fs/internal.h\n@@ -40,12 +40,18 @@ int __block_write_begin_int(struct folio *folio, loff_t pos, unsigned len,\n  */\n extern void __init chrdev_init(void);\n \n+/*\n+ * filesystems.c\n+ */\n+struct file_system_type *get_fs_type_noload(const char *name);\n+\n /*\n  * fs_context.c\n  */\n extern int parse_monolithic_mount_data(struct fs_context *, void *);\n extern void vfs_clean_context(struct fs_context *fc);\n extern int finish_clean_context(struct fs_context *fc);\n+struct fs_context *fs_context_for_unpriv_mount(struct file_system_type *fs_type);\n \n /*\n  * namei.c\ndiff --git a/fs/namespace.c b/fs/namespace.c\nindex aecd05ac01705d..36ed48c3f64678 100644\n--- a/fs/namespace.c\n+++ b/fs/namespace.c\n@@ -2202,7 +2202,8 @@ struct mnt_namespace *mnt_ns_from_dentry(struct dentry *dentry)\n \treturn to_mnt_ns(get_proc_ns(dentry-\u003ed_inode));\n }\n \n-static bool mnt_ns_loop(struct dentry *dentry)\n+static bool mnt_ns_loop_target(struct dentry *dentry,\n+\t\t\t       struct mnt_namespace *target_mnt_ns)\n {\n \t/* Could bind mounting the mount namespace inode cause a\n \t * mount namespace loop?\n@@ -2212,7 +2213,12 @@ static bool mnt_ns_loop(struct dentry *dentry)\n \tif (!mnt_ns)\n \t\treturn false;\n \n-\treturn current-\u003ensproxy-\u003emnt_ns-\u003ens.ns_id \u003e= mnt_ns-\u003ens.ns_id;\n+\treturn target_mnt_ns-\u003ens.ns_id \u003e= mnt_ns-\u003ens.ns_id;\n+}\n+\n+static bool mnt_ns_loop(struct dentry *dentry)\n+{\n+\treturn mnt_ns_loop_target(dentry, current-\u003ensproxy-\u003emnt_ns);\n }\n \n struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,\n@@ -2423,10 +2429,11 @@ static bool __has_children(struct mount *mnt, struct dentry *dentry)\n  *\n  * locks: mount_locked_reader || namespace_shared \u0026\u0026 pinned(subtree)\n  */\n-static bool check_for_nsfs_mounts(struct mount *subtree)\n+static bool check_for_nsfs_mounts(struct mount *subtree,\n+\t\t\t\t  struct mnt_namespace *target_mnt_ns)\n {\n \tfor (struct mount *p = subtree; p; p = next_mnt(p, subtree))\n-\t\tif (mnt_ns_loop(p-\u003emnt.mnt_root))\n+\t\tif (mnt_ns_loop_target(p-\u003emnt.mnt_root, target_mnt_ns))\n \t\t\treturn false;\n \treturn true;\n }\n@@ -2464,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)\n \t\tif (!anon_ns_root(old_mnt))\n \t\t\treturn ERR_PTR(-EINVAL);\n \n-\t\tif (!check_for_nsfs_mounts(old_mnt))\n+\t\tif (!check_for_nsfs_mounts(old_mnt, current-\u003ensproxy-\u003emnt_ns))\n \t\t\treturn ERR_PTR(-EINVAL);\n \t}\n \n@@ -2564,12 +2571,15 @@ int count_mounts(struct mnt_namespace *ns, struct mount *mnt)\n enum mnt_tree_flags_t {\n \tMNT_TREE_BENEATH = BIT(0),\n \tMNT_TREE_PROPAGATION = BIT(1),\n+\tMNT_TREE_MNTNS = BIT(2),\n+\tMNT_TREE_MNTNS_INIT = BIT(3),\n };\n \n /**\n  * attach_recursive_mnt - attach a source mount tree\n  * @source_mnt: mount tree to be attached\n  * @dest:\tthe context for mounting at the place where the tree should go\n+ * @move_mntns:\twhether @source_mnt is attached via MOVE_MOUNT_T_MNTNS\n  *\n  *  NOTE: in the table below explains the semantics when a source mount\n  *  of a given type is attached to a destination mount of a given type.\n@@ -2632,7 +2642,8 @@ enum mnt_tree_flags_t {\n  *         Otherwise a negative error code is returned.\n  */\n static int attach_recursive_mnt(struct mount *source_mnt,\n-\t\t\t\tconst struct pinned_mountpoint *dest)\n+\t\t\t\tconst struct pinned_mountpoint *dest,\n+\t\t\t\tbool move_mntns)\n {\n \tstruct mount *dest_mnt = dest-\u003eparent;\n \tstruct mountpoint *dest_mp = dest-\u003emp;\n@@ -2641,6 +2652,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,\n \tstruct user_namespace *user_ns = ns-\u003euser_ns;\n \tstruct pinned_mountpoint root = {};\n \tstruct mountpoint *shorter = NULL;\n+\tstruct mnt_namespace *src_ns;\n \tstruct mount *child, *p;\n \tstruct mount *top;\n \tstruct hlist_node *n;\n@@ -2662,6 +2674,7 @@ static int attach_recursive_mnt(struct mount *source_mnt,\n \t\tuser_ns = current-\u003ensproxy-\u003emnt_ns-\u003euser_ns;\n \telse\n \t\tuser_ns = ns-\u003euser_ns;\n+\tsrc_ns = moving ? NULL : source_mnt-\u003emnt_ns;\n \n \t/*\n \t * Preallocate a mountpoint in case the new mounts need to be\n@@ -2694,6 +2707,12 @@ static int attach_recursive_mnt(struct mount *source_mnt,\n \tif (err)\n \t\tgoto out_cleanup_ids;\n \n+\tif (move_mntns \u0026\u0026 src_ns \u0026\u0026 src_ns-\u003euser_ns != user_ns) {\n+\t\tlock_mnt_tree(source_mnt);\n+\t\tif (list_empty(\u0026source_mnt-\u003emnt_expire))\n+\t\t\tsource_mnt-\u003emnt.mnt_flags |= MNT_LOCKED;\n+\t}\n+\n \tif (IS_MNT_SHARED(dest_mnt)) {\n \t\tfor (p = source_mnt; p; p = next_mnt(p, source_mnt))\n \t\t\tset_mnt_shared(p);\n@@ -2937,7 +2956,7 @@ static int graft_tree(struct mount *mnt, const struct pinned_mountpoint *mp)\n \t      d_is_dir(mnt-\u003emnt.mnt_root))\n \t\treturn -ENOTDIR;\n \n-\treturn attach_recursive_mnt(mnt, mp);\n+\treturn attach_recursive_mnt(mnt, mp, false);\n }\n \n static int may_change_propagation(const struct mount *m)\n@@ -3131,7 +3150,7 @@ static int do_loopback(const struct path *path, const char *old_name,\n \t\treturn PTR_ERR(mnt);\n \n \t/* the copy may carry mount namespace files from below the source */\n-\tif (recurse \u0026\u0026 !check_for_nsfs_mounts(mnt))\n+\tif (recurse \u0026\u0026 !check_for_nsfs_mounts(mnt, current-\u003ensproxy-\u003emnt_ns))\n \t\terr = -EINVAL;\n \telse\n \t\terr = graft_tree(mnt, \u0026mp);\n@@ -3776,9 +3795,11 @@ static inline bool may_use_mount(struct mount *mnt)\n \n static int do_move_mount(const struct path *old_path,\n \t\t\t const struct path *new_path,\n-\t\t\t enum mnt_tree_flags_t flags)\n+\t\t\t enum mnt_tree_flags_t flags,\n+\t\t\t struct mnt_namespace *target_mnt_ns)\n {\n \tstruct mount *old = real_mount(old_path-\u003emnt);\n+\tstruct mnt_namespace *dest_mnt_ns;\n \tint err;\n \tbool beneath = flags \u0026 MNT_TREE_BENEATH;\n \n@@ -3792,7 +3813,23 @@ static int do_move_mount(const struct path *old_path,\n \tif (IS_ERR(mp.parent))\n \t\treturn PTR_ERR(mp.parent);\n \n-\tif (check_mnt(old)) {\n+\tif (flags \u0026 MNT_TREE_MNTNS) {\n+\t\tif (!anon_ns_root(old) || old-\u003emnt_ns == mp.parent-\u003emnt_ns ||\n+\t\t    mp.parent-\u003emnt_ns != target_mnt_ns)\n+\t\t\treturn -EINVAL;\n+\t\tif (flags \u0026 MNT_TREE_MNTNS_INIT) {\n+\t\t\tif (mp.parent != target_mnt_ns-\u003eroot)\n+\t\t\t\treturn -EBUSY;\n+\t\t} else if (mp.mp-\u003em_dentry == mp.parent-\u003emnt.mnt_root) {\n+\t\t\tconst struct mount *m = mp.parent;\n+\n+\t\t\twhile (m != target_mnt_ns-\u003eroot \u0026\u0026 mnt_has_parent(m) \u0026\u0026\n+\t\t\t       m-\u003emnt_mountpoint == m-\u003emnt_parent-\u003emnt.mnt_root)\n+\t\t\t\tm = m-\u003emnt_parent;\n+\t\t\tif (m == target_mnt_ns-\u003eroot)\n+\t\t\t\treturn beneath ? -EINVAL : -EBUSY;\n+\t\t}\n+\t} else if (check_mnt(old)) {\n \t\t/* if the source is in our namespace... */\n \t\t/* ... it should be detachable from parent */\n \t\tif (!mnt_has_parent(old) || IS_MNT_LOCKED(old))\n@@ -3840,12 +3877,14 @@ static int do_move_mount(const struct path *old_path,\n \t */\n \tif (IS_MNT_SHARED(mp.parent) \u0026\u0026 tree_contains_unbindable(old))\n \t\treturn -EINVAL;\n-\tif (!check_for_nsfs_mounts(old))\n+\tdest_mnt_ns = is_anon_ns(mp.parent-\u003emnt_ns) ?\n+\t\t      current-\u003ensproxy-\u003emnt_ns : mp.parent-\u003emnt_ns;\n+\tif (!check_for_nsfs_mounts(old, dest_mnt_ns))\n \t\treturn -ELOOP;\n \tif (mount_is_ancestor(old, mp.parent))\n \t\treturn -ELOOP;\n \n-\treturn attach_recursive_mnt(old, \u0026mp);\n+\treturn attach_recursive_mnt(old, \u0026mp, flags \u0026 MNT_TREE_MNTNS);\n }\n \n static int do_move_mount_old(const struct path *path, const char *old_name)\n@@ -3860,7 +3899,7 @@ static int do_move_mount_old(const struct path *path, const char *old_name)\n \tif (err)\n \t\treturn err;\n \n-\treturn do_move_mount(\u0026old_path, path, 0);\n+\treturn do_move_mount(\u0026old_path, path, 0, NULL);\n }\n \n /*\n@@ -4614,16 +4653,19 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n \tstruct vfsmount *new_mnt;\n \tstruct mount *mnt;\n \tunsigned int mnt_flags = 0;\n+\tbool priv;\n \tlong ret;\n \n \tif ((flags \u0026 ~(FSMOUNT_CLOEXEC | FSMOUNT_NAMESPACE)) != 0)\n \t\treturn -EINVAL;\n \n+\tpriv = may_mount();\n \tif ((flags \u0026 FSMOUNT_NAMESPACE) \u0026\u0026\n \t    !ns_capable(current_user_ns(), CAP_SYS_ADMIN))\n \t\treturn -EPERM;\n \n-\tif (!(flags \u0026 FSMOUNT_NAMESPACE) \u0026\u0026 !may_mount())\n+\tif (!(flags \u0026 FSMOUNT_NAMESPACE) \u0026\u0026 !IS_ENABLED(CONFIG_ROOTNS) \u0026\u0026\n+\t    !priv)\n \t\treturn -EPERM;\n \n \tif (attr_flags \u0026 ~FSMOUNT_VALID_FLAGS)\n@@ -4658,6 +4700,15 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n \tif (ret)\n \t\treturn ret;\n \n+\tif (fc-\u003erootns_bound) {\n+\t\tif (flags \u0026 FSMOUNT_NAMESPACE)\n+\t\t\treturn -EINVAL;\n+\t\tif (!ns_capable(fc-\u003euser_ns, CAP_SYS_ADMIN))\n+\t\t\treturn -EPERM;\n+\t} else if (!(flags \u0026 FSMOUNT_NAMESPACE) \u0026\u0026 !priv) {\n+\t\treturn -EPERM;\n+\t}\n+\n \t/* There must be a valid superblock or we can't mount it */\n \tret = -EINVAL;\n \tif (!fc-\u003eroot)\n@@ -4699,9 +4750,12 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n \t\treturn FD_ADD((flags \u0026 FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,\n \t\t\t      open_new_namespace(\u0026new_path, MOUNT_COPY_NEW));\n \n-\tns = alloc_mnt_ns(current-\u003ensproxy-\u003emnt_ns-\u003euser_ns, true);\n+\tns = alloc_mnt_ns(priv ? current-\u003ensproxy-\u003emnt_ns-\u003euser_ns :\n+\t\t\t  fc-\u003euser_ns, true);\n \tif (IS_ERR(ns))\n \t\treturn PTR_ERR(ns);\n+\tif (!priv)\n+\t\tns-\u003eseq_origin = fc-\u003erootns_mnt_id;\n \tmnt = real_mount(new_path.mnt);\n \tns-\u003eroot = mnt;\n \tns-\u003enr_mounts = 1;\n@@ -4725,7 +4779,8 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n \n static inline int vfs_move_mount(const struct path *from_path,\n \t\t\t\t const struct path *to_path,\n-\t\t\t\t enum mnt_tree_flags_t mflags)\n+\t\t\t\t enum mnt_tree_flags_t mflags,\n+\t\t\t\t struct mnt_namespace *target_mnt_ns)\n {\n \tint ret;\n \n@@ -4736,7 +4791,123 @@ static inline int vfs_move_mount(const struct path *from_path,\n \tif (mflags \u0026 MNT_TREE_PROPAGATION)\n \t\treturn do_set_group(from_path, to_path);\n \n-\treturn do_move_mount(from_path, to_path, mflags);\n+\treturn do_move_mount(from_path, to_path, mflags, target_mnt_ns);\n+}\n+\n+static int lookup_move_mount_from(int from_dfd,\n+\t\t\t\t  const char __user *from_pathname,\n+\t\t\t\t  unsigned int flags, struct path *from_path)\n+{\n+\tunsigned int uflags = 0;\n+\tunsigned int lflags = 0;\n+\n+\tif (flags \u0026 MOVE_MOUNT_F_EMPTY_PATH)\n+\t\tuflags = AT_EMPTY_PATH;\n+\n+\tCLASS(filename_maybe_null, from_name)(from_pathname, uflags);\n+\tif (!from_name \u0026\u0026 from_dfd \u003e= 0) {\n+\t\tCLASS(fd_raw, f_from)(from_dfd);\n+\t\tif (fd_empty(f_from))\n+\t\t\treturn -EBADF;\n+\n+\t\t*from_path = fd_file(f_from)-\u003ef_path;\n+\t\tpath_get(from_path);\n+\t\treturn 0;\n+\t}\n+\n+\tif (flags \u0026 MOVE_MOUNT_F_SYMLINKS)\n+\t\tlflags |= LOOKUP_FOLLOW;\n+\tif (flags \u0026 MOVE_MOUNT_F_AUTOMOUNTS)\n+\t\tlflags |= LOOKUP_AUTOMOUNT;\n+\treturn filename_lookup(from_dfd, from_name, lflags, from_path, NULL);\n+}\n+\n+/**\n+ * DOC: MOVE_MOUNT_T_MNTNS\n+ *\n+ * ``MOVE_MOUNT_T_MNTNS`` installs detached anonymous mount trees into a target\n+ * mount namespace ``nsfs`` file descriptor supplied as ``to_dfd``:\n+ *\n+ * 1. ``to_pathname`` of ``\"/\"`` attaches the initial root mount onto the\n+ *    ``nullfs`` root of an empty mount namespace at most once.\n+ *\n+ * 2. Relative ``to_pathname`` values resolve beneath the live root of the\n+ *    target mount namespace.\n+ *\n+ * Capability is checked against ``CAP_SYS_ADMIN`` in the target mount\n+ * namespace's owning user namespace, and source trees crossing user namespace\n+ * boundaries are locked with ``MNT_LOCKED`` and locked mount flags.\n+ */\n+static int move_mount_mntns(int from_dfd, const char __user *from_pathname,\n+\t\t\t    int to_dfd, const char __user *to_pathname,\n+\t\t\t    unsigned int flags, enum mnt_tree_flags_t mflags)\n+{\n+\tstruct path from_path __free(path_put) = {};\n+\tstruct path to_path __free(path_put) = {};\n+\tstruct mnt_namespace *target_mnt_ns;\n+\tunsigned int lflags;\n+\tstruct ns_common *ns;\n+\tbool is_root;\n+\tint ret;\n+\n+\tCLASS(filename_maybe_null, to_name)(to_pathname, AT_EMPTY_PATH);\n+\tif (IS_ERR(to_name))\n+\t\treturn PTR_ERR(to_name);\n+\tif (!to_name)\n+\t\treturn -EINVAL;\n+\n+\tCLASS(fd, f_mntns)(to_dfd);\n+\tif (fd_empty(f_mntns))\n+\t\treturn -EBADF;\n+\tif (!proc_ns_file(fd_file(f_mntns)))\n+\t\treturn -EINVAL;\n+\n+\tns = get_proc_ns(file_inode(fd_file(f_mntns)));\n+\tif (ns-\u003ens_type != CLONE_NEWNS)\n+\t\treturn -EINVAL;\n+\n+\ttarget_mnt_ns = to_mnt_ns(ns);\n+\tif (is_anon_ns(target_mnt_ns))\n+\t\treturn -EINVAL;\n+\tif (!ns_capable(target_mnt_ns-\u003euser_ns, CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\tis_root = to_name-\u003ename[0] == '/' \u0026\u0026 to_name-\u003ename[1] == '\\0';\n+\tif (is_root) {\n+\t\tif (flags \u0026 MOVE_MOUNT_BENEATH)\n+\t\t\treturn -EINVAL;\n+\n+\t\tto_path.mnt = mntget(\u0026target_mnt_ns-\u003eroot-\u003emnt);\n+\t\tto_path.dentry = dget(target_mnt_ns-\u003eroot-\u003emnt.mnt_root);\n+\t\tmflags |= MNT_TREE_MNTNS_INIT;\n+\t} else {\n+\t\tstruct path mntns_root __free(path_put) = {};\n+\n+\t\tif (to_name-\u003ename[0] == '/')\n+\t\t\treturn -EINVAL;\n+\n+\t\tret = mnt_ns_get_root(target_mnt_ns, \u0026mntns_root);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\n+\t\tlflags = LOOKUP_IN_ROOT;\n+\t\tif (flags \u0026 MOVE_MOUNT_T_SYMLINKS)\n+\t\t\tlflags |= LOOKUP_FOLLOW;\n+\t\tif (flags \u0026 MOVE_MOUNT_T_AUTOMOUNTS)\n+\t\t\tlflags |= LOOKUP_AUTOMOUNT;\n+\t\tret = filename_lookup(AT_FDCWD, to_name, lflags, \u0026to_path,\n+\t\t\t\t      \u0026mntns_root);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\n+\tret = lookup_move_mount_from(from_dfd, from_pathname, flags,\n+\t\t\t\t     \u0026from_path);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\treturn vfs_move_mount(\u0026from_path, \u0026to_path, mflags | MNT_TREE_MNTNS,\n+\t\t\t      target_mnt_ns);\n }\n \n /*\n@@ -4758,7 +4929,7 @@ SYSCALL_DEFINE5(move_mount,\n \tenum mnt_tree_flags_t mflags = 0;\n \tint ret = 0;\n \n-\tif (!may_mount())\n+\tif (!(flags \u0026 MOVE_MOUNT_T_MNTNS) \u0026\u0026 !may_mount())\n \t\treturn -EPERM;\n \n \tif (flags \u0026 ~MOVE_MOUNT__MASK)\n@@ -4771,6 +4942,13 @@ SYSCALL_DEFINE5(move_mount,\n \tif (flags \u0026 MOVE_MOUNT_SET_GROUP)\tmflags |= MNT_TREE_PROPAGATION;\n \tif (flags \u0026 MOVE_MOUNT_BENEATH)\t\tmflags |= MNT_TREE_BENEATH;\n \n+\tif (unlikely(flags \u0026 MOVE_MOUNT_T_MNTNS)) {\n+\t\tif (flags \u0026 (MOVE_MOUNT_T_EMPTY_PATH | MOVE_MOUNT_SET_GROUP))\n+\t\t\treturn -EINVAL;\n+\t\treturn move_mount_mntns(from_dfd, from_pathname,\n+\t\t\t\t\tto_dfd, to_pathname, flags, mflags);\n+\t}\n+\n \tuflags = 0;\n \tif (flags \u0026 MOVE_MOUNT_T_EMPTY_PATH)\n \t\tuflags = AT_EMPTY_PATH;\n@@ -4794,29 +4972,12 @@ SYSCALL_DEFINE5(move_mount,\n \t\t\treturn ret;\n \t}\n \n-\tuflags = 0;\n-\tif (flags \u0026 MOVE_MOUNT_F_EMPTY_PATH)\n-\t\tuflags = AT_EMPTY_PATH;\n-\n-\tCLASS(filename_maybe_null,from_name)(from_pathname, uflags);\n-\tif (!from_name \u0026\u0026 from_dfd \u003e= 0) {\n-\t\tCLASS(fd_raw, f_from)(from_dfd);\n-\t\tif (fd_empty(f_from))\n-\t\t\treturn -EBADF;\n-\n-\t\treturn vfs_move_mount(\u0026fd_file(f_from)-\u003ef_path, \u0026to_path, mflags);\n-\t}\n-\n-\tlflags = 0;\n-\tif (flags \u0026 MOVE_MOUNT_F_SYMLINKS)\n-\t\tlflags |= LOOKUP_FOLLOW;\n-\tif (flags \u0026 MOVE_MOUNT_F_AUTOMOUNTS)\n-\t\tlflags |= LOOKUP_AUTOMOUNT;\n-\tret = filename_lookup(from_dfd, from_name, lflags, \u0026from_path, NULL);\n+\tret = lookup_move_mount_from(from_dfd, from_pathname, flags,\n+\t\t\t\t     \u0026from_path);\n \tif (ret)\n \t\treturn ret;\n \n-\treturn vfs_move_mount(\u0026from_path, \u0026to_path, mflags);\n+\treturn vfs_move_mount(\u0026from_path, \u0026to_path, mflags, NULL);\n }\n \n /*\n@@ -6582,6 +6743,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,\n \t\t\t\tconst struct super_block *sb,\n \t\t\t\tint *new_mnt_flags)\n {\n+\tbool foreign_ns = !ns_capable_noaudit(ns-\u003euser_ns, CAP_SYS_ADMIN);\n \tint new_flags = *new_mnt_flags;\n \tstruct mount *mnt;\n \n@@ -6611,6 +6773,11 @@ static bool mnt_already_visible(struct mnt_namespace *ns,\n \t\t/* Don't miss readonly hidden in the superblock flags */\n \t\tif (sb_rdonly(mnt-\u003emnt.mnt_sb))\n \t\t\tmnt_flags |= MNT_LOCK_READONLY;\n+\t\tif (foreign_ns) {\n+\t\t\tif (mnt_flags \u0026 MNT_READONLY)\n+\t\t\t\tmnt_flags |= MNT_LOCK_READONLY;\n+\t\t\tmnt_flags |= MNT_LOCK_ATIME;\n+\t\t}\n \n \t\t/* Verify the mount flags are equal to or more permissive\n \t\t * than the proposed new mount.\n@@ -6629,7 +6796,7 @@ static bool mnt_already_visible(struct mnt_namespace *ns,\n \t\tlist_for_each_entry(child, \u0026mnt-\u003emnt_mounts, mnt_child) {\n \t\t\tstruct inode *inode = child-\u003emnt_mountpoint-\u003ed_inode;\n \t\t\t/* Only worry about locked mounts */\n-\t\t\tif (!(child-\u003emnt.mnt_flags \u0026 MNT_LOCKED))\n+\t\t\tif (!foreign_ns \u0026\u0026 !(child-\u003emnt.mnt_flags \u0026 MNT_LOCKED))\n \t\t\t\tcontinue;\n \t\t\t/* Is the directory permanently empty? */\n \t\t\tif (!is_empty_dir_inode(inode))\n@@ -6650,13 +6817,18 @@ static bool mount_too_revealing(const struct super_block *sb, int *new_mnt_flags\n \tstruct mnt_namespace *ns = current-\u003ensproxy-\u003emnt_ns;\n \tunsigned long s_iflags;\n \n-\tif (ns-\u003euser_ns == \u0026init_user_ns)\n-\t\treturn false;\n-\n \t/* Can this filesystem be too revealing? */\n \tif (!(sb-\u003es_type-\u003efs_flags \u0026 FS_USERNS_MOUNT_RESTRICTED))\n \t\treturn false;\n \n+\tif (ns-\u003euser_ns == \u0026init_user_ns \u0026\u0026\n+\t    ns_capable_noaudit(\u0026init_user_ns, CAP_SYS_ADMIN))\n+\t\treturn false;\n+\n+\tif (!ns_capable_noaudit(ns-\u003euser_ns, CAP_SYS_ADMIN) \u0026\u0026\n+\t    current_chrooted())\n+\t\treturn true;\n+\n \ts_iflags = sb-\u003es_iflags;\n \tif ((s_iflags \u0026 required_iflags) != required_iflags) {\n \t\tWARN_ONCE(1, \"Expected s_iflags to contain 0x%lx\\n\",\n@@ -6708,6 +6880,22 @@ static void mntns_put(struct ns_common *ns)\n \tput_mnt_ns(to_mnt_ns(ns));\n }\n \n+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root)\n+{\n+\tint err;\n+\n+\terr = vfs_path_lookup(mnt_ns-\u003eroot-\u003emnt.mnt_root, \u0026mnt_ns-\u003eroot-\u003emnt,\n+\t\t\t      \"/\", LOOKUP_DOWN, root);\n+\tif (err)\n+\t\treturn err;\n+\tif (root-\u003emnt == \u0026mnt_ns-\u003eroot-\u003emnt) {\n+\t\tpath_put(root);\n+\t\t*root = (struct path){};\n+\t\treturn -ENOENT;\n+\t}\n+\treturn 0;\n+}\n+\n static int mntns_install(struct nsset *nsset, struct ns_common *ns)\n {\n \tstruct nsproxy *nsproxy = nsset-\u003ensproxy;\ndiff --git a/fs/nsfs.c b/fs/nsfs.c\nindex 8179d69da03871..1de51cd475080e 100644\n--- a/fs/nsfs.c\n+++ b/fs/nsfs.c\n@@ -711,3 +711,67 @@ void nsproxy_ns_active_put(struct nsproxy *ns)\n \tns_ref_active_put(ns-\u003etime_ns);\n \tns_ref_active_put(ns-\u003etime_ns_for_children);\n }\n+\n+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,\n+\t\t\t   unsigned long nstype)\n+{\n+\tstruct ns_common *ns = NULL;\n+\n+\tswitch (nstype) {\n+\tcase CLONE_NEWNS:\n+\t\tif (ns_ref_get(nsp-\u003emnt_ns))\n+\t\t\tns = to_ns_common(nsp-\u003emnt_ns);\n+\t\tbreak;\n+#ifdef CONFIG_CGROUPS\n+\tcase CLONE_NEWCGROUP:\n+\t\tif (ns_ref_get(nsp-\u003ecgroup_ns))\n+\t\t\tns = to_ns_common(nsp-\u003ecgroup_ns);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_UTS_NS\n+\tcase CLONE_NEWUTS:\n+\t\tif (ns_ref_get(nsp-\u003euts_ns))\n+\t\t\tns = to_ns_common(nsp-\u003euts_ns);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_IPC_NS\n+\tcase CLONE_NEWIPC:\n+\t\tif (ns_ref_get(nsp-\u003eipc_ns))\n+\t\t\tns = to_ns_common(nsp-\u003eipc_ns);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_USER_NS\n+\tcase CLONE_NEWUSER:\n+\t\tif (ns_ref_get(user_ns))\n+\t\t\tns = to_ns_common(user_ns);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_PID_NS\n+\tcase CLONE_NEWPID:\n+\t\tif (ns_ref_get(nsp-\u003epid_ns_for_children))\n+\t\t\tns = to_ns_common(nsp-\u003epid_ns_for_children);\n+\t\tbreak;\n+#endif\n+#ifdef CONFIG_NET_NS\n+\tcase CLONE_NEWNET:\n+\t\tif (ns_ref_get(nsp-\u003enet_ns))\n+\t\t\tns = to_ns_common(nsp-\u003enet_ns);\n+\t\tbreak;\n+#endif\n+\tcase CLONE_NEWTIME:\n+#ifdef CONFIG_TIME_NS\n+\t\tif (ns_ref_get(nsp-\u003etime_ns))\n+\t\t\tns = to_ns_common(nsp-\u003etime_ns);\n+\t\tbreak;\n+#else\n+\t\treturn -EOPNOTSUPP;\n+#endif\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tif (!ns)\n+\t\treturn -ESRCH;\n+\n+\treturn open_namespace(ns);\n+}\ndiff --git a/fs/proc/root.c b/fs/proc/root.c\nindex 7fbbe92bf73a71..323296b030892d 100644\n--- a/fs/proc/root.c\n+++ b/fs/proc/root.c\n@@ -15,6 +15,8 @@\n #include \u003clinux/sched/stat.h\u003e\n #include \u003clinux/module.h\u003e\n #include \u003clinux/bitops.h\u003e\n+#include \u003clinux/nsproxy.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003clinux/user_namespace.h\u003e\n #include \u003clinux/fs_context.h\u003e\n #include \u003clinux/mount.h\u003e\n@@ -323,6 +325,21 @@ static int proc_get_tree(struct fs_context *fc)\n \treturn get_tree_nodev(fc, proc_fill_super);\n }\n \n+static int proc_set_rootns(struct fs_context *fc, struct rootns *rootns)\n+{\n+\tstruct proc_fs_context *ctx = fc-\u003efs_private;\n+\tstruct pid_namespace *target = rootns-\u003ens-\u003epid_ns_for_children;\n+\n+\tif (!pidns_is_ancestor(target, task_active_pid_ns(current)))\n+\t\treturn invalfc(fc, \"cannot set pidns to non-descendant pidns\");\n+\n+\tput_pid_ns(ctx-\u003epid_ns);\n+\tctx-\u003epid_ns = get_pid_ns(target);\n+\tput_user_ns(fc-\u003euser_ns);\n+\tfc-\u003euser_ns = get_user_ns(ctx-\u003epid_ns-\u003euser_ns);\n+\treturn 0;\n+}\n+\n static void proc_fs_context_free(struct fs_context *fc)\n {\n \tstruct proc_fs_context *ctx = fc-\u003efs_private;\n@@ -334,6 +351,7 @@ static void proc_fs_context_free(struct fs_context *fc)\n static const struct fs_context_operations proc_fs_context_ops = {\n \t.free\t\t= proc_fs_context_free,\n \t.parse_param\t= proc_parse_param,\n+\t.set_rootns\t= proc_set_rootns,\n \t.get_tree\t= proc_get_tree,\n \t.reconfigure\t= proc_reconfigure,\n };\ndiff --git a/include/linux/cred.h b/include/linux/cred.h\nindex 49c26af3734908..9849366fd44b87 100644\n--- a/include/linux/cred.h\n+++ b/include/linux/cred.h\n@@ -19,6 +19,7 @@\n \n struct cred;\n struct inode;\n+struct rootns;\n \n extern struct task_struct init_task;\n \n@@ -152,7 +153,8 @@ struct cred {\n \n extern void __put_cred(struct cred *);\n extern void exit_creds(struct task_struct *);\n-extern int copy_creds(struct task_struct *, u64);\n+int copy_creds(struct task_struct *tsk, u64 clone_flags,\n+\t       struct rootns *rootns);\n extern const struct cred *get_task_cred(struct task_struct *);\n extern struct cred *cred_alloc_blank(void);\n extern struct cred *prepare_creds(void);\ndiff --git a/include/linux/fs_context.h b/include/linux/fs_context.h\nindex d1727dffecc5e2..42648bec5cfa36 100644\n--- a/include/linux/fs_context.h\n+++ b/include/linux/fs_context.h\n@@ -21,6 +21,7 @@ struct file_system_type;\n struct mnt_namespace;\n struct net;\n struct pid_namespace;\n+struct rootns;\n struct super_block;\n struct user_namespace;\n struct vfsmount;\n@@ -36,6 +37,8 @@ enum fs_context_purpose {\n  * Userspace usage phase for fsopen/fspick.\n  */\n enum fs_context_phase {\n+\tFS_CONTEXT_AWAITING_NS,\t\t/* Unprivileged context awaiting target ns */\n+\tFS_CONTEXT_CREATE_NS,\t\t/* Set namespaces for sb creation */\n \tFS_CONTEXT_CREATE_PARAMS,\t/* Loading params for sb creation */\n \tFS_CONTEXT_CREATING,\t\t/* A superblock is being created */\n \tFS_CONTEXT_AWAITING_MOUNT,\t/* Superblock created, awaiting fsmount() */\n@@ -101,6 +104,7 @@ struct fs_context {\n \tconst char\t\t*source;\t/* The source name (eg. dev path) */\n \tvoid\t\t\t*security;\t/* LSM options */\n \tvoid\t\t\t*s_fs_info;\t/* Proposed s_fs_info */\n+\tu64\t\t\trootns_mnt_id;\t/* Target rootns mnt_ns ID */\n \tunsigned int\t\tsb_flags;\t/* Proposed superblock flags (SB_*) */\n \tunsigned int\t\tsb_flags_mask;\t/* Superblock flags that were changed */\n \tunsigned int\t\ts_iflags;\t/* OR'd with sb-\u003es_iflags */\n@@ -110,6 +114,7 @@ struct fs_context {\n \tbool\t\t\tglobal:1;\t/* Goes into \u0026init_user_ns */\n \tbool\t\t\toldapi:1;\t/* Coming from mount(2) */\n \tbool\t\t\texclusive:1;    /* create new superblock, reject existing one */\n+\tbool\t\t\trootns_bound:1;\t/* Bound via FSCONFIG_SET_ROOTNS */\n };\n \n struct fs_context_operations {\n@@ -117,6 +122,7 @@ struct fs_context_operations {\n \tint (*dup)(struct fs_context *fc, struct fs_context *src_fc);\n \tint (*parse_param)(struct fs_context *fc, struct fs_parameter *param);\n \tint (*parse_monolithic)(struct fs_context *fc, void *data);\n+\tint (*set_rootns)(struct fs_context *fc, struct rootns *rootns);\n \tint (*get_tree)(struct fs_context *fc);\n \tint (*reconfigure)(struct fs_context *fc);\n };\ndiff --git a/include/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h\nindex 87d9d06710cb26..2cb90ddedc14a2 100644\n--- a/include/linux/lsm_hook_defs.h\n+++ b/include/linux/lsm_hook_defs.h\n@@ -480,3 +480,10 @@ LSM_HOOK(int, 0, bdev_alloc_security, struct block_device *bdev)\n LSM_HOOK(void, LSM_RET_VOID, bdev_free_security, struct block_device *bdev)\n LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,\n \t enum lsm_integrity_type type, const void *value, size_t size)\n+\n+#ifdef CONFIG_ROOTNS\n+LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)\n+LSM_HOOK(void, LSM_RET_VOID, rootns_free, struct rootns *rootns)\n+LSM_HOOK(int, 0, rootns_clone, struct rootns *rootns)\n+LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)\n+#endif /* CONFIG_ROOTNS */\ndiff --git a/include/linux/lsm_hooks.h b/include/linux/lsm_hooks.h\nindex 13621e9e233e6b..217a59d428b158 100644\n--- a/include/linux/lsm_hooks.h\n+++ b/include/linux/lsm_hooks.h\n@@ -121,6 +121,9 @@ struct lsm_blob_sizes {\n \tunsigned int lbs_bpf_map;\n \tunsigned int lbs_bpf_prog;\n \tunsigned int lbs_bpf_token;\n+#ifdef CONFIG_ROOTNS\n+\tunsigned int lbs_rootns;\n+#endif\n };\n \n /*\ndiff --git a/include/linux/mnt_namespace.h b/include/linux/mnt_namespace.h\nindex 0acd1089d149cf..98188d1f74280c 100644\n--- a/include/linux/mnt_namespace.h\n+++ b/include/linux/mnt_namespace.h\n@@ -8,6 +8,7 @@\n \n struct mnt_namespace;\n struct fs_struct;\n+struct path;\n struct user_namespace;\n struct ns_common;\n \n@@ -15,6 +16,7 @@ extern struct mnt_namespace init_mnt_ns;\n \n extern struct mnt_namespace *copy_mnt_ns(u64, struct mnt_namespace *,\n \t\tstruct user_namespace *, struct fs_struct *);\n+int mnt_ns_get_root(struct mnt_namespace *mnt_ns, struct path *root);\n extern void put_mnt_ns(struct mnt_namespace *ns);\n DEFINE_FREE(put_mnt_ns, struct mnt_namespace *, if (!IS_ERR_OR_NULL(_T)) put_mnt_ns(_T))\n extern struct ns_common *from_mnt_ns(struct mnt_namespace *);\ndiff --git a/include/linux/nsfs.h b/include/linux/nsfs.h\nindex 731b67fc2fecd1..bfba790ee1a7fb 100644\n--- a/include/linux/nsfs.h\n+++ b/include/linux/nsfs.h\n@@ -39,5 +39,7 @@ void nsfs_init(void);\n \n void nsproxy_ns_active_get(struct nsproxy *ns);\n void nsproxy_ns_active_put(struct nsproxy *ns);\n+int nsproxy_open_namespace(struct nsproxy *nsp, struct user_namespace *user_ns,\n+\t\t\t   unsigned long nstype);\n \n #endif /* _LINUX_NSFS_H */\ndiff --git a/include/linux/nsproxy.h b/include/linux/nsproxy.h\nindex dc2447f5f09240..26b3b788cc909f 100644\n--- a/include/linux/nsproxy.h\n+++ b/include/linux/nsproxy.h\n@@ -12,6 +12,8 @@ struct ipc_namespace;\n struct pid_namespace;\n struct cgroup_namespace;\n struct fs_struct;\n+struct rootns;\n+struct user_namespace;\n \n /*\n  * A structure to contain pointers to all per-process\n@@ -92,7 +94,12 @@ static inline struct cred *nsset_cred(struct nsset *set)\n  *\n  */\n \n-int copy_namespaces(u64 flags, struct task_struct *tsk);\n+struct nsproxy *create_new_namespaces(u64 flags,\n+\t\t\t\t      struct nsproxy *ns,\n+\t\t\t\t      struct user_namespace *user_ns,\n+\t\t\t\t      struct fs_struct *new_fs);\n+int copy_namespaces(u64 flags, struct task_struct *tsk,\n+\t\t    struct rootns *rootns);\n void switch_cred_namespaces(const struct cred *old, const struct cred *new);\n void exit_nsproxy_namespaces(struct task_struct *tsk);\n void get_cred_namespaces(struct task_struct *tsk);\ndiff --git a/include/linux/pid_namespace.h b/include/linux/pid_namespace.h\nindex b20baaa7e62b75..6fd959f4d0d4da 100644\n--- a/include/linux/pid_namespace.h\n+++ b/include/linux/pid_namespace.h\n@@ -15,6 +15,7 @@\n #define MAX_PID_NS_LEVEL 32\n \n struct fs_pin;\n+struct rootns;\n \n #if defined(CONFIG_SYSCTL) \u0026\u0026 defined(CONFIG_MEMFD_CREATE)\n /* modes for vm.memfd_noexec sysctl */\n@@ -45,6 +46,9 @@ struct pid_namespace {\n \tstruct user_namespace *user_ns;\n \tstruct ucounts *ucounts;\n \tint reboot;\t/* group exit code if this pidns was rebooted */\n+#ifdef CONFIG_ROOTNS\n+\tstruct rootns *rootns;\n+#endif\n \tstruct ns_common ns;\n \tstruct work_struct\twork;\n } __randomize_layout;\ndiff --git a/include/linux/rootns.h b/include/linux/rootns.h\nnew file mode 100644\nindex 00000000000000..795a79584231d9\n--- /dev/null\n+++ b/include/linux/rootns.h\n@@ -0,0 +1,92 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.\n+ */\n+\n+#ifndef _LINUX_ROOTNS_H\n+#define _LINUX_ROOTNS_H\n+\n+#include \u003clinux/refcount.h\u003e\n+#include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/wait.h\u003e\n+\n+struct file;\n+struct kernel_clone_args;\n+struct nsproxy;\n+struct pid;\n+struct pid_namespace;\n+struct task_struct;\n+struct user_namespace;\n+\n+enum rootns_state {\n+\tROOTNS_INIT\t= 0,\n+\tROOTNS_FORKING\t= 1,\n+\tROOTNS_RUNNING\t= 2,\n+\tROOTNS_DEAD\t= 3,\n+};\n+\n+/*\n+ * The rootns object.\n+ */\n+struct rootns {\n+\trefcount_t\t\tusage;\n+\tint\t\t\texit_code;\t/* The exit code of 'init' */\n+#ifdef CONFIG_SECURITY\n+\tvoid\t\t\t*security;\t/* LSM security blob */\n+#endif\n+\tstruct user_namespace\t*user_ns;\t/* Owning user namespace */\n+\tstruct nsproxy\t\t*ns;\t\t/* This rootns's namespaces */\n+\tstruct pid\t\t*init_pid;\t/* The 'init' task's TGID (pid ref) */\n+\tspinlock_t\t\tlock;\t\t/* Guards rootns lifecycle state */\n+\twait_queue_head_t\twaitq;\t\t/* Someone waiting for init to exit waits here */\n+\tunsigned int\t\tflags;\t\t/* Validated rootns() flags */\n+\tenum rootns_state\tstate;\t\t/* Root namespace lifecycle state */\n+};\n+\n+#ifdef CONFIG_ROOTNS\n+struct rootns *get_rootns(struct rootns *c);\n+void put_rootns(struct rootns *c);\n+bool is_rootns_file(struct file *file);\n+void copy_rootns(struct task_struct *tsk, struct pid *pid,\n+\t\t struct rootns *rootns);\n+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk);\n+int rootns_prepare_fork(struct kernel_clone_args *args);\n+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p);\n+#else\n+static inline struct rootns *get_rootns(struct rootns *c)\n+{\n+\treturn NULL;\n+}\n+\n+static inline void put_rootns(struct rootns *c)\n+{\n+}\n+\n+static inline bool is_rootns_file(struct file *file)\n+{\n+\treturn false;\n+}\n+\n+static inline void copy_rootns(struct task_struct *tsk, struct pid *pid,\n+\t\t\t       struct rootns *rootns)\n+{\n+}\n+\n+static inline void exit_rootns(struct pid_namespace *pid_ns,\n+\t\t\t       struct task_struct *tsk)\n+{\n+}\n+\n+static inline int rootns_prepare_fork(struct kernel_clone_args *args)\n+{\n+\treturn -EINVAL;\n+}\n+\n+static inline int rootns_finish_fork(struct kernel_clone_args *args,\n+\t\t\t\t     struct task_struct *p)\n+{\n+\treturn 0;\n+}\n+#endif /* CONFIG_ROOTNS */\n+\n+#endif /* _LINUX_ROOTNS_H */\ndiff --git a/include/linux/sched/task.h b/include/linux/sched/task.h\nindex 90ed5bc3c7afee..e0c4e8ab02f154 100644\n--- a/include/linux/sched/task.h\n+++ b/include/linux/sched/task.h\n@@ -16,6 +16,8 @@ struct task_struct;\n struct rusage;\n union thread_union;\n struct css_set;\n+struct file;\n+struct rootns;\n \n /* All the bits taken by the old clone syscall. */\n #define CLONE_LEGACY_FLAGS 0xffffffffULL\n@@ -39,11 +41,17 @@ struct kernel_clone_args {\n \t/* Number of elements in *set_tid */\n \tsize_t set_tid_size;\n \tint cgroup;\n+\tint rootns_fd;\n \tint idle;\n \tint (*fn)(void *);\n \tvoid *fn_arg;\n \tstruct cgroup *cgrp;\n \tstruct css_set *cset;\n+#ifdef CONFIG_ROOTNS\n+\tstruct file *rootns_file;\n+\tstruct rootns *rootns;\n+\tbool rootns_bootstrapping;\n+#endif\n \tunsigned int kill_seq;\n };\n \ndiff --git a/include/linux/security.h b/include/linux/security.h\nindex 40831fab54709a..995292f1c92eb9 100644\n--- a/include/linux/security.h\n+++ b/include/linux/security.h\n@@ -84,6 +84,7 @@ struct audit_krule;\n struct ns_common;\n struct user_namespace;\n struct timezone;\n+struct rootns;\n \n enum lsm_event {\n \tLSM_POLICY_CHANGE,\n@@ -2469,4 +2470,33 @@ static inline void security_initramfs_populated(void)\n }\n #endif /* CONFIG_SECURITY */\n \n+#ifdef CONFIG_ROOTNS\n+#ifdef CONFIG_SECURITY\n+int security_rootns_alloc(struct rootns *rootns, unsigned int flags);\n+void security_rootns_free(struct rootns *rootns);\n+int security_rootns_clone(struct rootns *rootns);\n+int security_rootns_kill(struct rootns *rootns, int sig);\n+#else\n+static inline int security_rootns_alloc(struct rootns *rootns,\n+\t\t\t\t\tunsigned int flags)\n+{\n+\treturn 0;\n+}\n+\n+static inline void security_rootns_free(struct rootns *rootns)\n+{\n+}\n+\n+static inline int security_rootns_clone(struct rootns *rootns)\n+{\n+\treturn 0;\n+}\n+\n+static inline int security_rootns_kill(struct rootns *rootns, int sig)\n+{\n+\treturn 0;\n+}\n+#endif /* CONFIG_SECURITY */\n+#endif /* CONFIG_ROOTNS */\n+\n #endif /* ! __LINUX_SECURITY_H */\ndiff --git a/include/linux/syscalls.h b/include/linux/syscalls.h\nindex 552d9710a0d574..7e630b612ef26c 100644\n--- a/include/linux/syscalls.h\n+++ b/include/linux/syscalls.h\n@@ -1006,6 +1006,7 @@ asmlinkage long sys_lsm_get_self_attr(unsigned int attr, struct lsm_ctx __user *\n asmlinkage long sys_lsm_set_self_attr(unsigned int attr, struct lsm_ctx __user *ctx,\n \t\t\t\t      u32 size, u32 flags);\n asmlinkage long sys_lsm_list_modules(u64 __user *ids, u32 __user *size, u32 flags);\n+asmlinkage long sys_rootns(unsigned int flags);\n \n /*\n  * Architecture-specific system calls\ndiff --git a/include/linux/time_namespace.h b/include/linux/time_namespace.h\nindex 58bd9728df5838..bdc185543893df 100644\n--- a/include/linux/time_namespace.h\n+++ b/include/linux/time_namespace.h\n@@ -60,6 +60,15 @@ static inline void put_time_ns(struct time_namespace *ns)\n \t\tfree_time_ns(ns);\n }\n \n+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)\n+{\n+\tif (nsproxy-\u003etime_ns != nsproxy-\u003etime_ns_for_children) {\n+\t\tget_time_ns(nsproxy-\u003etime_ns_for_children);\n+\t\tput_time_ns(nsproxy-\u003etime_ns);\n+\t\tnsproxy-\u003etime_ns = nsproxy-\u003etime_ns_for_children;\n+\t}\n+}\n+\n void proc_timens_show_offsets(struct task_struct *p, struct seq_file *m);\n \n struct proc_timens_offset {\n@@ -125,6 +134,10 @@ static inline void put_time_ns(struct time_namespace *ns)\n {\n }\n \n+static inline void timens_activate_nsproxy(struct nsproxy *nsproxy)\n+{\n+}\n+\n static inline\n struct time_namespace *copy_time_ns(u64 flags,\n \t\t\t\t    struct user_namespace *user_ns,\ndiff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h\nindex 91232053775d8d..3600a903442e2b 100644\n--- a/include/linux/user_namespace.h\n+++ b/include/linux/user_namespace.h\n@@ -184,6 +184,7 @@ static inline struct user_namespace *get_user_ns(struct user_namespace *ns)\n }\n \n extern int create_user_ns(struct cred *new);\n+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns);\n extern int unshare_userns(unsigned long unshare_flags, struct cred **new_cred);\n extern void __put_user_ns(struct user_namespace *ns);\n \n@@ -226,6 +227,12 @@ static inline int create_user_ns(struct cred *new)\n \treturn -EINVAL;\n }\n \n+static inline int install_user_ns_cred(struct cred *cred,\n+\t\t\t\t       struct user_namespace *user_ns)\n+{\n+\treturn -EINVAL;\n+}\n+\n static inline int unshare_userns(unsigned long unshare_flags,\n \t\t\t\t struct cred **new_cred)\n {\ndiff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h\nindex 5b7e77a7c736ee..25902ed39d79c3 100644\n--- a/include/uapi/asm-generic/unistd.h\n+++ b/include/uapi/asm-generic/unistd.h\n@@ -867,8 +867,12 @@ __SYSCALL(__NR_rseq_slice_yield, sys_rseq_slice_yield)\n #define __NR_fchroot 472\n __SYSCALL(__NR_fchroot, sys_fchroot)\n \n+/* kernel/rootns.c */\n+#define __NR_rootns 473\n+__SYSCALL(__NR_rootns, sys_rootns)\n+\n #undef __NR_syscalls\n-#define __NR_syscalls 473\n+#define __NR_syscalls 474\n \n /*\n  * 32 bit systems traditionally used different\ndiff --git a/include/uapi/linux/mount.h b/include/uapi/linux/mount.h\nindex ac865edac5173e..7fa93de08ceb6c 100644\n--- a/include/uapi/linux/mount.h\n+++ b/include/uapi/linux/mount.h\n@@ -75,9 +75,10 @@\n #define MOVE_MOUNT_T_SYMLINKS\t\t0x00000010 /* Follow symlinks on to path */\n #define MOVE_MOUNT_T_AUTOMOUNTS\t\t0x00000020 /* Follow automounts on to path */\n #define MOVE_MOUNT_T_EMPTY_PATH\t\t0x00000040 /* Empty to path permitted */\n+#define MOVE_MOUNT_T_MNTNS\t\t0x00000080 /* Resolve to_dfd as mntns fd */\n #define MOVE_MOUNT_SET_GROUP\t\t0x00000100 /* Set sharing group instead */\n #define MOVE_MOUNT_BENEATH\t\t0x00000200 /* Mount beneath top mount */\n-#define MOVE_MOUNT__MASK\t\t0x00000377\n+#define MOVE_MOUNT__MASK\t\t0x000003f7\n \n /*\n  * fsopen() flags.\n@@ -105,6 +106,7 @@ enum fsconfig_command {\n \tFSCONFIG_CMD_CREATE\t= 6,\t/* Create new or reuse existing superblock */\n \tFSCONFIG_CMD_RECONFIGURE = 7,\t/* Invoke superblock reconfiguration */\n \tFSCONFIG_CMD_CREATE_EXCL = 8,\t/* Create new superblock, fail if reusing existing superblock */\n+\tFSCONFIG_SET_ROOTNS\t= 9,\t/* Set a rootns, supplied by fd */\n };\n \n /*\ndiff --git a/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h\nnew file mode 100644\nindex 00000000000000..acd91d895c632d\n--- /dev/null\n+++ b/include/uapi/linux/rootns.h\n@@ -0,0 +1,83 @@\n+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */\n+/*\n+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.\n+ * Copyright (C) 2026 Opinsys Oy\n+ */\n+\n+#ifndef _UAPI_LINUX_ROOTNS_H\n+#define _UAPI_LINUX_ROOTNS_H\n+\n+#include \u003clinux/ioctl.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+/**\n+ * enum rootns_flags - Flags for rootns()\n+ * @ROOTNS_KILL_ON_CLOSE: Send %SIGKILL to rootns init on final fd release.\n+ * @ROOTNS_CLOSE_ON_EXEC: Set %O_CLOEXEC on the returned control fd.\n+ * @ROOTNS_ALL_FLAGS: Mask of all valid flags accepted by rootns().\n+ *\n+ * Every root namespace allocates a full set of detached namespaces owned\n+ * by a fresh user namespace.\n+ */\n+enum rootns_flags {\n+\tROOTNS_KILL_ON_CLOSE\t= 0x00000001,\n+\tROOTNS_CLOSE_ON_EXEC\t= 0x00000002,\n+\tROOTNS_ALL_FLAGS\t= 0x00000003,\n+};\n+\n+/**\n+ * struct rootns_wait_args - Arguments for %ROOTNS_WAIT\n+ * @flags: Wait options (0 or %WNOHANG).\n+ * @status: Output wait status of rootns init in waitpid(2) format.\n+ */\n+struct rootns_wait_args {\n+\t__u32 flags;\n+\t__s32 status;\n+};\n+\n+#define ROOTNS_IOCTL_MAGIC\t0xB9\n+\n+/**\n+ * DOC: ROOTNS_GET_NSFD\n+ *\n+ * ``ioctl(rootnsfd, ROOTNS_GET_NSFD, nstype)`` opens an ``nsfs`` file\n+ * descriptor (with ``O_CLOEXEC``) for the member namespace identified by\n+ * ``nstype`` (one of ``CLONE_NEWNS``, ``CLONE_NEWCGROUP``,\n+ * ``CLONE_NEWUTS``, ``CLONE_NEWIPC``, ``CLONE_NEWUSER``, ``CLONE_NEWPID``,\n+ * ``CLONE_NEWNET``, or ``CLONE_NEWTIME``).\n+ *\n+ * Requires ``CAP_SYS_ADMIN`` in the ``rootns`` user namespace. Opening\n+ * ``CLONE_NEWPID`` additionally requires running in an ancestor active PID\n+ * namespace and that ``rootns`` init is running.\n+ */\n+#define ROOTNS_GET_NSFD\t\t_IO(ROOTNS_IOCTL_MAGIC, 0x01)\n+\n+/**\n+ * DOC: ROOTNS_WAIT\n+ *\n+ * ``ioctl(rootnsfd, ROOTNS_WAIT, \u0026args)`` waits interruptibly (unless\n+ * ``WNOHANG`` is set in ``args.flags``) until ``rootnsfd`` reaches\n+ * ``ROOTNS_DEAD``, then writes the recorded exit status of ``rootns`` init\n+ * into ``args.status``.\n+ *\n+ * Returns the caller-visible TGID of ``rootns`` init on success, ``0`` if\n+ * ``WNOHANG`` is set and the ``rootns`` has not terminated, or ``-1`` with\n+ * ``errno`` set to ``ECHILD`` if init was never started or is not visible in\n+ * the caller's active PID namespace.\n+ */\n+#define ROOTNS_WAIT\t\t_IOWR(ROOTNS_IOCTL_MAGIC, 0x02, struct rootns_wait_args)\n+\n+/**\n+ * DOC: ROOTNS_KILL\n+ *\n+ * ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` walks the target root namespace's PID\n+ * namespace IDR under ``tasklist_lock`` and delivers ``sig`` (or ``0`` for a\n+ * permission check) once to each member thread group.\n+ *\n+ * Returns ``0`` if at least one thread group was signaled, or ``-1`` with\n+ * ``errno`` set to ``EXDEV`` if the caller's active PID namespace is not an\n+ * ancestor or ``ESRCH`` if the ``rootns`` is not running or has no members.\n+ */\n+#define ROOTNS_KILL\t\t_IO(ROOTNS_IOCTL_MAGIC, 0x03)\n+\n+#endif /* _UAPI_LINUX_ROOTNS_H */\ndiff --git a/include/uapi/linux/sched.h b/include/uapi/linux/sched.h\nindex 19ffeba894283e..405cfc954ae181 100644\n--- a/include/uapi/linux/sched.h\n+++ b/include/uapi/linux/sched.h\n@@ -40,6 +40,7 @@\n #define CLONE_NNP\t\t(1ULL \u003c\u003c 35) /* Set no_new_privs on child. */\n #define CLONE_PIDFD_AUTOKILL\t(1ULL \u003c\u003c 36) /* Kill child when clone pidfd closes. */\n #define CLONE_EMPTY_MNTNS\t(1ULL \u003c\u003c 37) /* Create an empty mount namespace. */\n+#define CLONE_INTO_ROOTNS\t(1ULL \u003c\u003c 38) /* Clone into a specific root namespace. */\n \n /*\n  * cloning flags intersect with CSIGNAL so can be used with unshare and clone3\n@@ -94,6 +95,8 @@\n  *                kernel's limit of nested PID namespaces.\n  * @cgroup:       If CLONE_INTO_CGROUP is specified set this to\n  *                a file descriptor for the cgroup.\n+ * @rootns:       If CLONE_INTO_ROOTNS is specified set this to\n+ *                a file descriptor for the root namespace.\n  *\n  * The structure is versioned by size and thus extensible.\n  * New struct members must go at the end of the struct and\n@@ -111,12 +114,14 @@ struct clone_args {\n \t__aligned_u64 set_tid;\n \t__aligned_u64 set_tid_size;\n \t__aligned_u64 cgroup;\n+\t__aligned_u64 rootns;\n };\n #endif\n \n #define CLONE_ARGS_SIZE_VER0 64 /* sizeof first published struct */\n #define CLONE_ARGS_SIZE_VER1 80 /* sizeof second published struct */\n #define CLONE_ARGS_SIZE_VER2 88 /* sizeof third published struct */\n+#define CLONE_ARGS_SIZE_VER3 96 /* sizeof fourth published struct */\n \n /*\n  * Scheduling policies\ndiff --git a/init/Kconfig b/init/Kconfig\nindex c8a7cfa60a6ea4..ed93dd11e6ac1f 100644\n--- a/init/Kconfig\n+++ b/init/Kconfig\n@@ -1281,6 +1281,15 @@ config NET_NS\n \t  Allow user space to create what appear to be multiple instances\n \t  of the network stack.\n \n+config ROOTNS\n+\tbool \"Root namespace\"\n+\tdepends on USER_NS \u0026\u0026 PID_NS \u0026\u0026 UTS_NS \u0026\u0026 IPC_NS \u0026\u0026 NET_NS \u0026\u0026 CGROUPS\n+\thelp\n+\t  Allow user space to create and manage isolated root namespaces\n+\t  with their own mount tree, user namespace, namespace set, and init\n+\t  process lifecycle via rootns(), rootns ioctls, and clone3() with\n+\t  CLONE_INTO_ROOTNS.\n+\n endif # NAMESPACES\n \n config CHECKPOINT_RESTORE\ndiff --git a/ipc/mqueue.c b/ipc/mqueue.c\nindex 322c3dd98c4477..f94e9b566bd03b 100644\n--- a/ipc/mqueue.c\n+++ b/ipc/mqueue.c\n@@ -32,6 +32,7 @@\n #include \u003clinux/mutex.h\u003e\n #include \u003clinux/nsproxy.h\u003e\n #include \u003clinux/pid.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003clinux/ipc_namespace.h\u003e\n #include \u003clinux/user_namespace.h\u003e\n #include \u003clinux/slab.h\u003e\n@@ -400,6 +401,17 @@ static struct inode *mqueue_get_inode(struct super_block *sb,\n \treturn ERR_PTR(ret);\n }\n \n+static int mqueue_set_rootns(struct fs_context *fc, struct rootns *rootns)\n+{\n+\tstruct mqueue_fs_context *ctx = fc-\u003efs_private;\n+\n+\tput_ipc_ns(ctx-\u003eipc_ns);\n+\tctx-\u003eipc_ns = get_ipc_ns(rootns-\u003ens-\u003eipc_ns);\n+\tput_user_ns(fc-\u003euser_ns);\n+\tfc-\u003euser_ns = get_user_ns(ctx-\u003eipc_ns-\u003euser_ns);\n+\treturn 0;\n+}\n+\n static int mqueue_fill_super(struct super_block *sb, struct fs_context *fc)\n {\n \tstruct inode *inode;\n@@ -1613,6 +1625,7 @@ static const struct super_operations mqueue_super_ops = {\n \n static const struct fs_context_operations mqueue_fs_context_ops = {\n \t.free\t\t= mqueue_fs_context_free,\n+\t.set_rootns\t= mqueue_set_rootns,\n \t.get_tree\t= mqueue_get_tree,\n };\n \ndiff --git a/kernel/Makefile b/kernel/Makefile\nindex 4ff92e24680c52..7074d2664ce711 100644\n--- a/kernel/Makefile\n+++ b/kernel/Makefile\n@@ -152,6 +152,8 @@ KCOV_INSTRUMENT_kstack_erase.o := n\n \n obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o\n \n+obj-$(CONFIG_ROOTNS) += rootns.o\n+\n $(obj)/configs.o: $(obj)/config_data.gz\n \n # .config is small, so it is compressed with gzip rather than the image compressor.\ndiff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c\nindex 468e63dbd922d0..bbcf1433fdc25a 100644\n--- a/kernel/bpf/bpf_lsm.c\n+++ b/kernel/bpf/bpf_lsm.c\n@@ -16,6 +16,7 @@\n #include \u003clinux/btf_ids.h\u003e\n #include \u003clinux/ima.h\u003e\n #include \u003clinux/bpf-cgroup.h\u003e\n+#include \u003clinux/rootns.h\u003e\n \n /* For every LSM hook that allows attachment of BPF programs, declare a nop\n  * function where a BPF program can be attached. Notably, we qualify each with\n@@ -404,6 +405,11 @@ BTF_ID(func, bpf_lsm_task_setscheduler)\n BTF_ID(func, bpf_lsm_userns_create)\n BTF_ID(func, bpf_lsm_bdev_alloc_security)\n BTF_ID(func, bpf_lsm_bdev_setintegrity)\n+#ifdef CONFIG_ROOTNS\n+BTF_ID(func, bpf_lsm_rootns_alloc)\n+BTF_ID(func, bpf_lsm_rootns_clone)\n+BTF_ID(func, bpf_lsm_rootns_kill)\n+#endif /* CONFIG_ROOTNS */\n BTF_SET_END(sleepable_lsm_hooks)\n \n BTF_SET_START(untrusted_lsm_hooks)\n@@ -420,6 +426,10 @@ BTF_ID(func, bpf_lsm_sk_free_security)\n BTF_ID(func, bpf_lsm_task_free)\n BTF_ID(func, bpf_lsm_bdev_alloc_security)\n BTF_ID(func, bpf_lsm_bdev_free_security)\n+#ifdef CONFIG_ROOTNS\n+BTF_ID(func, bpf_lsm_rootns_alloc)\n+BTF_ID(func, bpf_lsm_rootns_free)\n+#endif /* CONFIG_ROOTNS */\n BTF_SET_END(untrusted_lsm_hooks)\n \n bool bpf_lsm_is_sleepable_hook(u32 btf_id)\ndiff --git a/kernel/cred.c b/kernel/cred.c\nindex d01df40a9a3861..48a8852dab4a06 100644\n--- a/kernel/cred.c\n+++ b/kernel/cred.c\n@@ -12,13 +12,16 @@\n #include \u003clinux/slab.h\u003e\n #include \u003clinux/sched.h\u003e\n #include \u003clinux/sched/coredump.h\u003e\n+#include \u003clinux/sched/exec_state.h\u003e\n #include \u003clinux/key.h\u003e\n #include \u003clinux/keyctl.h\u003e\n #include \u003clinux/init_task.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003clinux/security.h\u003e\n #include \u003clinux/binfmts.h\u003e\n #include \u003clinux/cn_proc.h\u003e\n #include \u003clinux/uidgid.h\u003e\n+#include \u003clinux/user_namespace.h\u003e\n \n #if 0\n #define kdebug(FMT, ...)\t\t\t\t\t\t\\\n@@ -251,6 +254,9 @@ struct cred *prepare_exec_creds(void)\n \treturn new;\n }\n \n+static bool cred_cap_issubset(const struct cred *set,\n+\t\t\t      const struct cred *subset);\n+\n /*\n  * Copy credentials for the new process created by fork()\n  *\n@@ -260,7 +266,8 @@ struct cred *prepare_exec_creds(void)\n  * The new process gets the current process's subjective credentials as its\n  * objective and subjective credentials\n  */\n-int copy_creds(struct task_struct *p, u64 clone_flags)\n+int copy_creds(struct task_struct *p, u64 clone_flags,\n+\t       struct rootns *rootns)\n {\n \tstruct cred *new;\n \tint ret;\n@@ -287,6 +294,29 @@ int copy_creds(struct task_struct *p, u64 clone_flags)\n \tif (!new)\n \t\treturn -ENOMEM;\n \n+\tif (rootns) {\n+\t\tconst struct cred *old = current_cred();\n+\n+\t\tif (!ns_capable(rootns-\u003euser_ns, CAP_SYS_ADMIN) ||\n+\t\t    !ns_capable(rootns-\u003euser_ns, CAP_SYS_CHROOT)) {\n+\t\t\tret = -EPERM;\n+\t\t\tgoto error_put;\n+\t\t}\n+\t\tif (new-\u003euser_ns != rootns-\u003euser_ns) {\n+\t\t\tret = install_user_ns_cred(new, rootns-\u003euser_ns);\n+\t\t\tif (ret \u003c 0)\n+\t\t\t\tgoto error_put;\n+\t\t}\n+\t\tif (!cred_cap_issubset(old, new) ||\n+\t\t    old-\u003euser_ns != new-\u003euser_ns) {\n+\t\t\tstruct task_exec_state *exec_state;\n+\n+\t\t\texec_state = rcu_dereference_protected(p-\u003eexec_state, true);\n+\t\t\tif (exec_state != \u0026init_task_exec_state)\n+\t\t\t\tWRITE_ONCE(exec_state-\u003edumpable, suid_dumpable);\n+\t\t}\n+\t}\n+\n \tif (clone_flags \u0026 CLONE_NEWUSER) {\n \t\tret = create_user_ns(new);\n \t\tif (ret \u003c 0)\ndiff --git a/kernel/fork.c b/kernel/fork.c\nindex 5efceb8d58a78b..ac0497ff410cb9 100644\n--- a/kernel/fork.c\n+++ b/kernel/fork.c\n@@ -65,6 +65,7 @@\n #include \u003clinux/rcupdate.h\u003e\n #include \u003clinux/ptrace.h\u003e\n #include \u003clinux/mount.h\u003e\n+#include \u003clinux/mnt_namespace.h\u003e\n #include \u003clinux/audit.h\u003e\n #include \u003clinux/memcontrol.h\u003e\n #include \u003clinux/ftrace.h\u003e\n@@ -83,6 +84,7 @@\n #include \u003clinux/fs_struct.h\u003e\n #include \u003clinux/magic.h\u003e\n #include \u003clinux/perf_event.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003clinux/posix-timers.h\u003e\n #include \u003clinux/user-return-notifier.h\u003e\n #include \u003clinux/oom.h\u003e\n@@ -1615,7 +1617,7 @@ static int copy_exec_state(u64 clone_flags, struct task_struct *tsk)\n \tstruct task_exec_state *exec_state;\n \n \t/* CLONE_VM siblings refcount-share the parent's exec_state. */\n-\tif (clone_flags \u0026 CLONE_VM) {\n+\tif ((clone_flags \u0026 (CLONE_VM | CLONE_INTO_ROOTNS)) == CLONE_VM) {\n \t\texec_state = rcu_dereference_protected(current-\u003eexec_state, true);\n \t\trefcount_inc(\u0026exec_state-\u003ecount);\n \t\trcu_assign_pointer(tsk-\u003eexec_state, exec_state);\n@@ -1631,8 +1633,30 @@ enum copy_fs_flags_t {\n \tCOPY_FS_IDLE\t= (1 \u003c\u003c 1),\n };\n \n+#ifdef CONFIG_ROOTNS\n+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)\n+{\n+\treturn args-\u003erootns;\n+}\n+\n+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)\n+{\n+\treturn args-\u003erootns_bootstrapping;\n+}\n+#else\n+static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)\n+{\n+\treturn NULL;\n+}\n+\n+static inline bool clone_args_rootns_bootstrapping(const struct kernel_clone_args *args)\n+{\n+\treturn false;\n+}\n+#endif\n+\n static int copy_fs(u64 clone_flags, struct task_struct *tsk,\n-\t\t   enum copy_fs_flags_t flags)\n+\t\t   enum copy_fs_flags_t flags, struct rootns *rootns)\n {\n \tstruct fs_struct *fs;\n \n@@ -1648,7 +1672,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,\n \t\tif (current-\u003ensproxy-\u003emnt_ns != \u0026init_mnt_ns)\n \t\t\treturn -EINVAL;\n \t\tfs = userspace_init_fs;\n-\t} else if (flags \u0026 COPY_FS_IDLE) {\n+\t} else if (flags \u0026 COPY_FS_IDLE || rootns) {\n \t\tfs = \u0026init_fs;\n \t} else {\n \t\tfs = current-\u003efs;\n@@ -1670,6 +1694,21 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk,\n \ttsk-\u003ereal_fs = tsk-\u003efs = copy_fs_struct(fs);\n \tif (!tsk-\u003efs)\n \t\treturn -ENOMEM;\n+\tif (rootns) {\n+\t\tstruct path root __free(path_put) = {};\n+\t\tint err;\n+\n+\t\terr = mnt_ns_get_root(rootns-\u003ens-\u003emnt_ns, \u0026root);\n+\t\tif (err) {\n+\t\t\tfree_fs_struct(tsk-\u003efs);\n+\t\t\ttsk-\u003ereal_fs = NULL;\n+\t\t\ttsk-\u003efs = NULL;\n+\t\t\treturn err;\n+\t\t}\n+\t\ttsk-\u003efs-\u003eumask = READ_ONCE(current-\u003efs-\u003eumask);\n+\t\tset_fs_root(tsk-\u003efs, \u0026root);\n+\t\tset_fs_pwd(tsk-\u003efs, \u0026root);\n+\t}\n \treturn 0;\n }\n \n@@ -2185,7 +2224,7 @@ __latent_entropy struct task_struct *copy_process(\n #ifdef CONFIG_PROVE_LOCKING\n \tDEBUG_LOCKS_WARN_ON(!p-\u003esoftirqs_enabled);\n #endif\n-\tretval = copy_creds(p, clone_flags);\n+\tretval = copy_creds(p, clone_flags, clone_args_rootns(args));\n \tif (retval \u003c 0)\n \t\tgoto bad_fork_free;\n \n@@ -2316,7 +2355,8 @@ __latent_entropy struct task_struct *copy_process(\n \t\tgoto bad_fork_cleanup_semundo;\n \tretval = copy_fs(clone_flags, p,\n \t\t\t (args-\u003eumh ? COPY_FS_UMH : 0) |\n-\t\t\t (args-\u003eidle ? COPY_FS_IDLE : 0));\n+\t\t\t (args-\u003eidle ? COPY_FS_IDLE : 0),\n+\t\t\t clone_args_rootns(args));\n \tif (retval)\n \t\tgoto bad_fork_cleanup_semundo;\n \tretval = copy_sighand(clone_flags, p);\n@@ -2328,7 +2368,7 @@ __latent_entropy struct task_struct *copy_process(\n \tretval = copy_mm(clone_flags, p);\n \tif (retval)\n \t\tgoto bad_fork_cleanup_signal;\n-\tretval = copy_namespaces(clone_flags, p);\n+\tretval = copy_namespaces(clone_flags, p, clone_args_rootns(args));\n \tif (retval)\n \t\tgoto bad_fork_cleanup_mm;\n \tretval = copy_io(clone_flags, p);\n@@ -2509,6 +2549,12 @@ __latent_entropy struct task_struct *copy_process(\n \t\tgoto bad_fork_core_free;\n \t}\n \n+\tif (unlikely(clone_args_rootns_bootstrapping(args) \u0026\u0026\n+\t\t     !is_child_reaper(pid))) {\n+\t\tretval = -EBUSY;\n+\t\tgoto bad_fork_core_free;\n+\t}\n+\n \t/* Let kill terminate clone/fork in the middle */\n \tif (fatal_signal_pending(current)) {\n \t\tretval = -EINTR;\n@@ -2576,6 +2622,8 @@ __latent_entropy struct task_struct *copy_process(\n \t\t\t\t\t  \u0026p-\u003esignal-\u003ethread_head);\n \t\t}\n \t\tattach_pid(p, PIDTYPE_PID);\n+\t\tif (thread_group_leader(p))\n+\t\t\tcopy_rootns(p, pid, clone_args_rootns(args));\n \t\tnr_threads++;\n \t}\n \ttotal_forks++;\n@@ -2777,6 +2825,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)\n \tif (!valid_signal(args-\u003eexit_signal))\n \t\treturn -EINVAL;\n \n+\tif (unlikely(clone_flags \u0026 CLONE_INTO_ROOTNS)) {\n+\t\tint err = rootns_prepare_fork(args);\n+\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n \t/*\n \t * Determine whether and which event to report to ptracer.  When\n \t * called from kernel_thread or CLONE_UNTRACED is explicitly\n@@ -2798,6 +2853,13 @@ pid_t kernel_clone(struct kernel_clone_args *args)\n \tp = copy_process(NULL, trace, NUMA_NO_NODE, args);\n \tadd_latent_entropy();\n \n+\tif (unlikely(clone_flags \u0026 CLONE_INTO_ROOTNS)) {\n+\t\tint err = rootns_finish_fork(args, p);\n+\n+\t\tif (err)\n+\t\t\treturn err;\n+\t}\n+\n \tif (IS_ERR(p))\n \t\treturn PTR_ERR(p);\n \n@@ -2955,7 +3017,9 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,\n \t\t     CLONE_ARGS_SIZE_VER1);\n \tBUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=\n \t\t     CLONE_ARGS_SIZE_VER2);\n-\tBUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER2);\n+\tBUILD_BUG_ON(offsetofend(struct clone_args, rootns) !=\n+\t\t     CLONE_ARGS_SIZE_VER3);\n+\tBUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);\n \n \tif (unlikely(usize \u003e PAGE_SIZE))\n \t\treturn -E2BIG;\n@@ -2985,6 +3049,10 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,\n \t    (args.cgroup \u003e INT_MAX || usize \u003c CLONE_ARGS_SIZE_VER2))\n \t\treturn -EINVAL;\n \n+\tif ((args.flags \u0026 CLONE_INTO_ROOTNS) \u0026\u0026\n+\t    (args.rootns \u003e INT_MAX || usize \u003c CLONE_ARGS_SIZE_VER3))\n+\t\treturn -EINVAL;\n+\n \t*kargs = (struct kernel_clone_args){\n \t\t.flags\t\t= args.flags,\n \t\t.pidfd\t\t= u64_to_user_ptr(args.pidfd),\n@@ -2996,6 +3064,7 @@ static noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,\n \t\t.tls\t\t= args.tls,\n \t\t.set_tid_size\t= args.set_tid_size,\n \t\t.cgroup\t\t= args.cgroup,\n+\t\t.rootns_fd\t= args.rootns,\n \t};\n \n \tif (args.set_tid \u0026\u0026\n@@ -3036,13 +3105,19 @@ static inline bool clone3_stack_valid(struct kernel_clone_args *kargs)\n \treturn true;\n }\n \n+#define CLONE_INTO_ROOTNS_FLAGS \\\n+\t(CLONE_INTO_ROOTNS | CLONE_VFORK | CLONE_PIDFD | \\\n+\t CLONE_CLEAR_SIGHAND | CLONE_INTO_CGROUP | CLONE_AUTOREAP | \\\n+\t CLONE_NNP | CLONE_PIDFD_AUTOKILL)\n+\n static bool clone3_args_valid(struct kernel_clone_args *kargs)\n {\n \t/* Verify that no unknown flags are passed along. */\n \tif (kargs-\u003eflags \u0026\n \t    ~(CLONE_LEGACY_FLAGS | CLONE_CLEAR_SIGHAND |\n \t      CLONE_INTO_CGROUP | CLONE_AUTOREAP | CLONE_NNP |\n-\t      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS))\n+\t      CLONE_PIDFD_AUTOKILL | CLONE_EMPTY_MNTNS |\n+\t      CLONE_INTO_ROOTNS))\n \t\treturn false;\n \n \t/*\n@@ -3060,6 +3135,10 @@ static bool clone3_args_valid(struct kernel_clone_args *kargs)\n \t    kargs-\u003eexit_signal)\n \t\treturn false;\n \n+\tif ((kargs-\u003eflags \u0026 CLONE_INTO_ROOTNS) \u0026\u0026\n+\t    (kargs-\u003eflags \u0026 ~CLONE_INTO_ROOTNS_FLAGS))\n+\t\treturn false;\n+\n \tif (!clone3_stack_valid(kargs))\n \t\treturn false;\n \ndiff --git a/kernel/nsproxy.c b/kernel/nsproxy.c\nindex 2dcf105e8ee2d4..78a1e1fb2cfd7f 100644\n--- a/kernel/nsproxy.c\n+++ b/kernel/nsproxy.c\n@@ -13,6 +13,7 @@\n #include \u003clinux/export.h\u003e\n #include \u003clinux/nsproxy.h\u003e\n #include \u003clinux/ns/ns_common_types.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003clinux/init_task.h\u003e\n #include \u003clinux/mnt_namespace.h\u003e\n #include \u003clinux/utsname.h\u003e\n@@ -85,9 +86,10 @@ void deactivate_nsproxy(struct nsproxy *ns)\n  * Return the newly created nsproxy.  Do not attach this to the task,\n  * leave it to the caller to do proper locking and attach it to task.\n  */\n-static struct nsproxy *create_new_namespaces(u64 flags,\n-\tstruct task_struct *tsk, struct user_namespace *user_ns,\n-\tstruct fs_struct *new_fs)\n+struct nsproxy *create_new_namespaces(u64 flags,\n+\t\t\t\t      struct nsproxy *ns,\n+\t\t\t\t      struct user_namespace *user_ns,\n+\t\t\t\t      struct fs_struct *new_fs)\n {\n \tstruct nsproxy *new_nsp;\n \tint err;\n@@ -96,52 +98,51 @@ static struct nsproxy *create_new_namespaces(u64 flags,\n \tif (!new_nsp)\n \t\treturn ERR_PTR(-ENOMEM);\n \n-\tnew_nsp-\u003emnt_ns = copy_mnt_ns(flags, tsk-\u003ensproxy-\u003emnt_ns,\n-\t\t\t\t      user_ns, new_fs);\n+\tnew_nsp-\u003emnt_ns = copy_mnt_ns(flags, ns-\u003emnt_ns, user_ns, new_fs);\n \tif (IS_ERR(new_nsp-\u003emnt_ns)) {\n \t\terr = PTR_ERR(new_nsp-\u003emnt_ns);\n \t\tgoto out_ns;\n \t}\n \n-\tnew_nsp-\u003euts_ns = copy_utsname(flags, user_ns, tsk-\u003ensproxy-\u003euts_ns);\n+\tnew_nsp-\u003euts_ns = copy_utsname(flags, user_ns, ns-\u003euts_ns);\n \tif (IS_ERR(new_nsp-\u003euts_ns)) {\n \t\terr = PTR_ERR(new_nsp-\u003euts_ns);\n \t\tgoto out_uts;\n \t}\n \n-\tnew_nsp-\u003eipc_ns = copy_ipcs(flags, user_ns, tsk-\u003ensproxy-\u003eipc_ns);\n+\tnew_nsp-\u003eipc_ns = copy_ipcs(flags, user_ns, ns-\u003eipc_ns);\n \tif (IS_ERR(new_nsp-\u003eipc_ns)) {\n \t\terr = PTR_ERR(new_nsp-\u003eipc_ns);\n \t\tgoto out_ipc;\n \t}\n \n \tnew_nsp-\u003epid_ns_for_children =\n-\t\tcopy_pid_ns(flags, user_ns, tsk-\u003ensproxy-\u003epid_ns_for_children);\n+\t\tcopy_pid_ns(flags, user_ns, ns-\u003epid_ns_for_children);\n \tif (IS_ERR(new_nsp-\u003epid_ns_for_children)) {\n \t\terr = PTR_ERR(new_nsp-\u003epid_ns_for_children);\n \t\tgoto out_pid;\n \t}\n \n \tnew_nsp-\u003ecgroup_ns = copy_cgroup_ns(flags, user_ns,\n-\t\t\t\t\t    tsk-\u003ensproxy-\u003ecgroup_ns);\n+\t\t\t\t\t    ns-\u003ecgroup_ns);\n \tif (IS_ERR(new_nsp-\u003ecgroup_ns)) {\n \t\terr = PTR_ERR(new_nsp-\u003ecgroup_ns);\n \t\tgoto out_cgroup;\n \t}\n \n-\tnew_nsp-\u003enet_ns = copy_net_ns(flags, user_ns, tsk-\u003ensproxy-\u003enet_ns);\n+\tnew_nsp-\u003enet_ns = copy_net_ns(flags, user_ns, ns-\u003enet_ns);\n \tif (IS_ERR(new_nsp-\u003enet_ns)) {\n \t\terr = PTR_ERR(new_nsp-\u003enet_ns);\n \t\tgoto out_net;\n \t}\n \n \tnew_nsp-\u003etime_ns_for_children = copy_time_ns(flags, user_ns,\n-\t\t\t\t\ttsk-\u003ensproxy-\u003etime_ns_for_children);\n+\t\t\t\t\tns-\u003etime_ns_for_children);\n \tif (IS_ERR(new_nsp-\u003etime_ns_for_children)) {\n \t\terr = PTR_ERR(new_nsp-\u003etime_ns_for_children);\n \t\tgoto out_time;\n \t}\n-\tnew_nsp-\u003etime_ns = get_time_ns(tsk-\u003ensproxy-\u003etime_ns);\n+\tnew_nsp-\u003etime_ns = get_time_ns(ns-\u003etime_ns);\n \n \treturn new_nsp;\n \n@@ -166,12 +167,18 @@ static struct nsproxy *create_new_namespaces(u64 flags,\n  * called from clone.  This now handles copy for nsproxy and all\n  * namespaces therein.\n  */\n-int copy_namespaces(u64 flags, struct task_struct *tsk)\n+int copy_namespaces(u64 flags, struct task_struct *tsk,\n+\t\t    struct rootns *rootns)\n {\n \tstruct nsproxy *old_ns = tsk-\u003ensproxy;\n \tstruct user_namespace *user_ns = task_cred_xxx(tsk, user_ns);\n \tstruct nsproxy *new_ns;\n \n+\tif (rootns) {\n+\t\tget_nsproxy(rootns-\u003ens);\n+\t\ttsk-\u003ensproxy = rootns-\u003ens;\n+\t\treturn 0;\n+\t}\n \tif (likely(!(flags \u0026 (CLONE_NS_ALL \u0026 ~CLONE_NEWUSER)))) {\n \t\tif ((flags \u0026 CLONE_VM) ||\n \t\t    likely(old_ns-\u003etime_ns_for_children == old_ns-\u003etime_ns)) {\n@@ -192,7 +199,7 @@ int copy_namespaces(u64 flags, struct task_struct *tsk)\n \t\t(CLONE_NEWIPC | CLONE_SYSVSEM))\n \t\treturn -EINVAL;\n \n-\tnew_ns = create_new_namespaces(flags, tsk, user_ns, tsk-\u003efs);\n+\tnew_ns = create_new_namespaces(flags, old_ns, user_ns, tsk-\u003efs);\n \tif (IS_ERR(new_ns))\n \t\treturn  PTR_ERR(new_ns);\n \n@@ -231,7 +238,7 @@ int unshare_nsproxy_namespaces(unsigned long unshare_flags,\n \t\tflags |= CLONE_EMPTY_MNTNS;\n \t}\n \n-\t*new_nsp = create_new_namespaces(flags, current, user_ns,\n+\t*new_nsp = create_new_namespaces(flags, current-\u003ensproxy, user_ns,\n \t\t\t\t\t new_fs ? new_fs : current-\u003efs);\n \tif (IS_ERR(*new_nsp)) {\n \t\terr = PTR_ERR(*new_nsp);\n@@ -289,7 +296,7 @@ int exec_task_namespaces(void)\n \tif (tsk-\u003ensproxy-\u003etime_ns_for_children == tsk-\u003ensproxy-\u003etime_ns)\n \t\treturn 0;\n \n-\tnew = create_new_namespaces(0, tsk, current_user_ns(), tsk-\u003efs);\n+\tnew = create_new_namespaces(0, tsk-\u003ensproxy, current_user_ns(), tsk-\u003efs);\n \tif (IS_ERR(new))\n \t\treturn PTR_ERR(new);\n \n@@ -356,7 +363,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset)\n \tstruct task_struct *me = current;\n \n \tnsset-\u003eflags = flags;\n-\tnsset-\u003ensproxy = create_new_namespaces(0, me, current_user_ns(), me-\u003efs);\n+\tnsset-\u003ensproxy = create_new_namespaces(0, me-\u003ensproxy, current_user_ns(), me-\u003efs);\n \tif (IS_ERR(nsset-\u003ensproxy))\n \t\treturn PTR_ERR(nsset-\u003ensproxy);\n \ndiff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c\nindex 127a5fd23e7040..081c27aa85bd18 100644\n--- a/kernel/pid_namespace.c\n+++ b/kernel/pid_namespace.c\n@@ -24,6 +24,7 @@\n #include \u003clinux/sched/signal.h\u003e\n #include \u003clinux/idr.h\u003e\n #include \u003clinux/nstree.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003cuapi/linux/wait.h\u003e\n #include \"pid_sysctl.h\"\n \n@@ -280,6 +281,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)\n \t\tcurrent-\u003esignal-\u003egroup_exit_code = pid_ns-\u003ereboot;\n \n \tacct_exit_ns(pid_ns);\n+\texit_rootns(pid_ns, me);\n \treturn;\n }\n \ndiff --git a/kernel/rootns.c b/kernel/rootns.c\nnew file mode 100644\nindex 00000000000000..3733a249fecaa1\n--- /dev/null\n+++ b/kernel/rootns.c\n@@ -0,0 +1,581 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.\n+ */\n+\n+/**\n+ * DOC: Overview\n+ *\n+ * A root namespace binds a full set of detached namespaces, an initially empty\n+ * mount namespace, an owning user namespace, and an init process behind a\n+ * pollable control file descriptor:\n+ *\n+ * 1. ``rootns()`` allocates a detached ``rootns`` with a fresh user namespace\n+ *    and dedicated mount (``CLONE_EMPTY_MNTNS``), PID, UTS, IPC, network,\n+ *    cgroup, and time namespaces, returning its control fd.\n+ *\n+ * 2. Userspace configures superblocks via ``FSCONFIG_SET_ROOTNS``, retrieves\n+ *    the mount namespace fd via ``ioctl(rootnsfd, ROOTNS_GET_NSFD,\n+ *    CLONE_NEWNS)``, and installs ``\"/\"`` and relative submounts via\n+ *    ``MOVE_MOUNT_T_MNTNS``.\n+ *\n+ * 3. ``clone3()`` with ``CLONE_INTO_ROOTNS`` spawns processes into the\n+ *    ``rootns``; the first call commits PID 1 while concurrent bootstrap\n+ *    callers wait killably.\n+ *\n+ * 4. ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` signals all member thread groups.\n+ *    When PID 1 exits, the PID namespace zaps and reaps all remaining tasks,\n+ *    ``poll()`` reports ``EPOLLHUP``, and ``ioctl(rootnsfd, ROOTNS_WAIT,\n+ *    \u0026args)`` returns init's exit status.\n+ */\n+\n+#include \u003clinux/poll.h\u003e\n+#include \u003clinux/wait.h\u003e\n+#include \u003cuapi/linux/wait.h\u003e\n+#include \u003clinux/file.h\u003e\n+#include \u003clinux/fs.h\u003e\n+#include \u003clinux/fs_struct.h\u003e\n+#include \u003clinux/anon_inodes.h\u003e\n+#include \u003clinux/rootns.h\u003e\n+#include \u003clinux/sched/signal.h\u003e\n+#include \u003clinux/sched/task.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/syscalls.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n+#include \u003clinux/mnt_namespace.h\u003e\n+#include \u003clinux/nsproxy.h\u003e\n+#include \u003clinux/ns_common.h\u003e\n+#include \u003clinux/nsfs.h\u003e\n+#include \u003clinux/pid.h\u003e\n+#include \u003clinux/pid_namespace.h\u003e\n+#include \u003clinux/time_namespace.h\u003e\n+#include \u003clinux/user_namespace.h\u003e\n+#include \u003clinux/compat.h\u003e\n+#include \u003clinux/idr.h\u003e\n+#include \u003clinux/security.h\u003e\n+#include \u003cuapi/linux/rootns.h\u003e\n+\n+/*\n+ * Get a reference to a rootns.\n+ */\n+struct rootns *get_rootns(struct rootns *c)\n+{\n+\trefcount_inc(\u0026c-\u003eusage);\n+\treturn c;\n+}\n+\n+static void free_rootns(struct rootns *c)\n+{\n+\tif (c-\u003ens)\n+\t\tput_nsproxy(c-\u003ens);\n+\tif (c-\u003einit_pid)\n+\t\tput_pid(c-\u003einit_pid);\n+\tif (c-\u003euser_ns) {\n+\t\tns_ref_active_put(c-\u003euser_ns);\n+\t\tput_user_ns(c-\u003euser_ns);\n+\t}\n+\tkfree(c);\n+}\n+\n+/*\n+ * Drop a reference on a rootns and clear it if it is no longer in use.\n+ */\n+void put_rootns(struct rootns *c)\n+{\n+\tif (!c || !refcount_dec_and_test(\u0026c-\u003eusage))\n+\t\treturn;\n+\n+\tsecurity_rootns_free(c);\n+\tfree_rootns(c);\n+}\n+\n+/*\n+ * Allow the user to poll for the rootns dying.\n+ */\n+static __poll_t rootns_poll(struct file *file, poll_table *wait)\n+{\n+\tstruct rootns *rootns = file-\u003eprivate_data;\n+\t__poll_t mask = 0;\n+\n+\tpoll_wait(file, \u0026rootns-\u003ewaitq, wait);\n+\n+\tif (READ_ONCE(rootns-\u003estate) == ROOTNS_DEAD)\n+\t\tmask |= EPOLLHUP;\n+\n+\treturn mask;\n+}\n+\n+static long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)\n+{\n+\tif (nstype \u003e UINT_MAX)\n+\t\treturn -EINVAL;\n+\tif (!ns_capable(rootns-\u003euser_ns, CAP_SYS_ADMIN))\n+\t\treturn -EPERM;\n+\n+\tif (nstype == CLONE_NEWPID) {\n+\t\tif (!pidns_is_ancestor(rootns-\u003ens-\u003epid_ns_for_children,\n+\t\t\t\t       task_active_pid_ns(current)))\n+\t\t\treturn -EXDEV;\n+\t\tif (READ_ONCE(rootns-\u003estate) != ROOTNS_RUNNING)\n+\t\t\treturn -ESRCH;\n+\t}\n+\n+\treturn nsproxy_open_namespace(rootns-\u003ens, rootns-\u003euser_ns, nstype);\n+}\n+\n+static long rootns_wait(struct rootns *rootns, void __user *uarg)\n+{\n+\tstruct pid_namespace *pid_ns = task_active_pid_ns(current);\n+\tstruct rootns_wait_args args;\n+\tlong ret;\n+\n+\tif (!uarg)\n+\t\treturn -EINVAL;\n+\tif (copy_from_user(\u0026args, uarg, sizeof(args)))\n+\t\treturn -EFAULT;\n+\tif (args.flags \u0026 ~WNOHANG)\n+\t\treturn -EINVAL;\n+\tif (READ_ONCE(rootns-\u003estate) == ROOTNS_INIT)\n+\t\treturn -ECHILD;\n+\n+\tif (!(args.flags \u0026 WNOHANG)) {\n+\t\tret = wait_event_freezable(rootns-\u003ewaitq,\n+\t\t\t\t\t   READ_ONCE(rootns-\u003estate) == ROOTNS_DEAD ||\n+\t\t\t\t\t   READ_ONCE(rootns-\u003estate) == ROOTNS_INIT);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\n+\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n+\t\tif (rootns-\u003estate == ROOTNS_INIT)\n+\t\t\treturn -ECHILD;\n+\t\tif (rootns-\u003estate != ROOTNS_DEAD)\n+\t\t\treturn 0;\n+\t\tret = pid_nr_ns(rootns-\u003einit_pid, pid_ns);\n+\t\tif (ret \u003c= 0)\n+\t\t\treturn -ECHILD;\n+\t\targs.status = rootns-\u003eexit_code;\n+\t}\n+\n+\tif (copy_to_user(uarg, \u0026args, sizeof(args)))\n+\t\treturn -EFAULT;\n+\treturn ret;\n+}\n+\n+static int rootns_kill_members(struct rootns *rootns, int sig)\n+{\n+\tstruct pid_namespace *pid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n+\tbool any_success = false;\n+\tbool any_other = false;\n+\tbool any_perm = false;\n+\tint other_err = 0;\n+\tstruct pid *pid;\n+\tint ret;\n+\tint nr;\n+\n+\tif (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))\n+\t\treturn -EXDEV;\n+\tif (READ_ONCE(rootns-\u003estate) != ROOTNS_RUNNING)\n+\t\treturn -ESRCH;\n+\n+\tret = security_rootns_kill(rootns, sig);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tscoped_guard(rcu) {\n+\t\tread_lock(\u0026tasklist_lock);\n+\t\tidr_for_each_entry(\u0026pid_ns-\u003eidr, pid, nr) {\n+\t\t\tstruct task_struct *task = pid_task(pid, PIDTYPE_TGID);\n+\t\t\tint err;\n+\n+\t\t\tif (!task)\n+\t\t\t\tcontinue;\n+\n+\t\t\terr = group_send_sig_info(sig, SEND_SIG_NOINFO, task,\n+\t\t\t\t\t\t  PIDTYPE_MAX);\n+\t\t\tif (!err) {\n+\t\t\t\tany_success = true;\n+\t\t\t} else if (err == -EPERM) {\n+\t\t\t\tany_perm = true;\n+\t\t\t} else if (err != -ESRCH \u0026\u0026 !any_other) {\n+\t\t\t\tany_other = true;\n+\t\t\t\tother_err = err;\n+\t\t\t}\n+\t\t}\n+\t\tread_unlock(\u0026tasklist_lock);\n+\t}\n+\n+\tif (any_success)\n+\t\treturn 0;\n+\tif (any_other)\n+\t\treturn other_err;\n+\tif (any_perm)\n+\t\treturn -EPERM;\n+\treturn -ESRCH;\n+}\n+\n+static long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n+{\n+\tstruct rootns *rootns = file-\u003eprivate_data;\n+\n+\tswitch (cmd) {\n+\tcase ROOTNS_GET_NSFD:\n+\t\treturn rootns_get_nsfd(rootns, arg);\n+\tcase ROOTNS_WAIT:\n+\t\treturn rootns_wait(rootns, (void __user *)arg);\n+\tcase ROOTNS_KILL:\n+\t\tif (arg \u003e INT_MAX || !valid_signal(arg))\n+\t\t\treturn -EINVAL;\n+\t\treturn rootns_kill_members(rootns, arg);\n+\tdefault:\n+\t\treturn -ENOIOCTLCMD;\n+\t}\n+}\n+\n+#ifdef CONFIG_COMPAT\n+static long rootns_compat_ioctl(struct file *file, unsigned int cmd,\n+\t\t\t\tunsigned long arg)\n+{\n+\tswitch (cmd) {\n+\tcase ROOTNS_WAIT:\n+\t\treturn rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));\n+\tcase ROOTNS_GET_NSFD:\n+\tcase ROOTNS_KILL:\n+\t\treturn rootns_ioctl(file, cmd, arg);\n+\tdefault:\n+\t\treturn -ENOIOCTLCMD;\n+\t}\n+}\n+#endif\n+\n+static int __rootns_kill(struct rootns *rootns, int sig, bool priv)\n+{\n+\tstruct pid *pid = NULL;\n+\tint ret;\n+\n+\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n+\t\tif (rootns-\u003estate == ROOTNS_RUNNING)\n+\t\t\tpid = get_pid(rootns-\u003einit_pid);\n+\t}\n+\tif (!pid)\n+\t\treturn -ESRCH;\n+\n+\tret = kill_pid(pid, sig, priv);\n+\tput_pid(pid);\n+\treturn ret;\n+}\n+\n+static int rootns_release(struct inode *inode, struct file *file)\n+{\n+\tstruct rootns *rootns = file-\u003eprivate_data;\n+\n+\tif (rootns-\u003eflags \u0026 ROOTNS_KILL_ON_CLOSE)\n+\t\t__rootns_kill(rootns, SIGKILL, true);\n+\tput_rootns(rootns);\n+\treturn 0;\n+}\n+\n+static const struct file_operations rootns_fops = {\n+\t.poll\t\t= rootns_poll,\n+\t.unlocked_ioctl\t= rootns_ioctl,\n+#ifdef CONFIG_COMPAT\n+\t.compat_ioctl\t= rootns_compat_ioctl,\n+#endif\n+\t.release\t= rootns_release,\n+};\n+\n+/*\n+ * Returns true if the file is a rootns.\n+ */\n+bool is_rootns_file(struct file *file)\n+{\n+\treturn file-\u003ef_op == \u0026rootns_fops;\n+}\n+\n+void copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)\n+{\n+\tif (likely(!c || !is_child_reaper(pid)))\n+\t\treturn;\n+\n+\tscoped_guard(spinlock, \u0026c-\u003elock) {\n+\t\tif (c-\u003estate != ROOTNS_FORKING)\n+\t\t\treturn;\n+\t\tns_of_pid(pid)-\u003erootns = get_rootns(c);\n+\t\tWRITE_ONCE(c-\u003einit_pid, get_pid(pid));\n+\t\tWRITE_ONCE(c-\u003estate, ROOTNS_RUNNING);\n+\t}\n+\twake_up_all(\u0026c-\u003ewaitq);\n+}\n+\n+void exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)\n+{\n+\tstruct rootns *c = pid_ns-\u003erootns;\n+\tstruct task_struct *leader;\n+\tint status;\n+\n+\tif (!c)\n+\t\treturn;\n+\n+\tleader = tsk-\u003egroup_leader;\n+\tstatus = (tsk-\u003esignal-\u003eflags \u0026 SIGNAL_GROUP_EXIT) ?\n+\t\t tsk-\u003esignal-\u003egroup_exit_code : leader-\u003eexit_code;\n+\n+\tscoped_guard(spinlock, \u0026c-\u003elock) {\n+\t\tc-\u003eexit_code = status;\n+\t\tWRITE_ONCE(c-\u003estate, ROOTNS_DEAD);\n+\t}\n+\n+\tpid_ns-\u003erootns = NULL;\n+\twake_up_poll(\u0026c-\u003ewaitq, EPOLLHUP);\n+\tput_rootns(c);\n+}\n+\n+static struct user_namespace *create_rootns_user_ns(void)\n+{\n+\tstruct user_namespace *user_ns;\n+\tstruct cred *new;\n+\tint ret;\n+\n+\tnew = prepare_creds();\n+\tif (!new)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\n+\tret = create_user_ns(new);\n+\tif (ret \u003c 0) {\n+\t\tabort_creds(new);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\n+\tuser_ns = get_user_ns(new-\u003euser_ns);\n+\tabort_creds(new);\n+\treturn user_ns;\n+}\n+\n+/*\n+ * Create a new rootns.\n+ */\n+static struct rootns *create_rootns(unsigned int flags)\n+{\n+\tu64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |\n+\t\t\t  CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |\n+\t\t\t  CLONE_NEWNET |\n+\t\t\t  (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);\n+\tstruct user_namespace *user_ns;\n+\tstruct nsproxy *ns;\n+\tstruct rootns *c;\n+\tint ret;\n+\n+\tc = kzalloc_obj(*c, GFP_KERNEL);\n+\tif (!c)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\n+\tinit_waitqueue_head(\u0026c-\u003ewaitq);\n+\tspin_lock_init(\u0026c-\u003elock);\n+\trefcount_set(\u0026c-\u003eusage, 1);\n+\tc-\u003eflags = flags;\n+\n+\tuser_ns = create_rootns_user_ns();\n+\tif (IS_ERR(user_ns)) {\n+\t\tret = PTR_ERR(user_ns);\n+\t\tgoto err_free;\n+\t}\n+\tc-\u003euser_ns = user_ns;\n+\tns_ref_active_get(user_ns);\n+\n+\tif (!ns_capable(user_ns, CAP_SYS_ADMIN)) {\n+\t\tret = -EPERM;\n+\t\tgoto err_free;\n+\t}\n+\n+\tns = create_new_namespaces(clone_flags, current-\u003ensproxy, user_ns,\n+\t\t\t\t   NULL);\n+\tif (IS_ERR(ns)) {\n+\t\tret = PTR_ERR(ns);\n+\t\tgoto err_free;\n+\t}\n+\n+\ttimens_activate_nsproxy(ns);\n+\tc-\u003ens = ns;\n+\tnsproxy_ns_active_get(ns);\n+\n+\tret = security_rootns_alloc(c, flags);\n+\tif (ret \u003c 0)\n+\t\tgoto err_free;\n+\n+\treturn c;\n+\n+err_free:\n+\tfree_rootns(c);\n+\treturn ERR_PTR(ret);\n+}\n+\n+/**\n+ * sys_rootns - Create a detached root namespace\n+ * @flags: Combination of \u0026enum rootns_flags values\n+ *\n+ * Allocate a detached root namespace owning a fresh user namespace and\n+ * dedicated empty mount, PID, UTS, IPC, network, cgroup, and time namespaces.\n+ *\n+ * Return: Control file descriptor on success, negative error code on failure.\n+ */\n+SYSCALL_DEFINE1(rootns, unsigned int, flags)\n+{\n+\tstruct rootns *c;\n+\tint fd;\n+\n+\tif (flags \u0026 ~ROOTNS_ALL_FLAGS)\n+\t\treturn -EINVAL;\n+\tif (unlikely(!current-\u003ensproxy))\n+\t\treturn -EOPNOTSUPP;\n+\n+\tc = create_rootns(flags);\n+\tif (IS_ERR(c))\n+\t\treturn PTR_ERR(c);\n+\n+\tfd = anon_inode_getfd(\"rootns\", \u0026rootns_fops, c,\n+\t\t\t      O_RDWR | (flags \u0026 ROOTNS_CLOSE_ON_EXEC ? O_CLOEXEC : 0));\n+\tif (fd \u003c 0)\n+\t\tput_rootns(c);\n+\n+\treturn fd;\n+}\n+\n+/**\n+ * DOC: CLONE_INTO_ROOTNS\n+ *\n+ * Passing ``CLONE_INTO_ROOTNS`` in ``struct clone_args.flags`` (with\n+ * ``size \u003e= CLONE_ARGS_SIZE_VER3``) spawns the child process into the root\n+ * namespace identified by ``struct clone_args.rootns``.\n+ *\n+ * Once ``\"/\"`` is mounted in the root namespace's mount namespace, the first\n+ * caller transitions the ``rootns`` from ``ROOTNS_INIT`` through\n+ * ``ROOTNS_FORKING`` to ``ROOTNS_RUNNING`` as PID 1 of its PID namespace\n+ * while concurrent bootstrap callers wait killably. Subsequent callers join\n+ * the running PID namespace until teardown begins.\n+ *\n+ * The caller must hold ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target\n+ * user namespace (and ``CAP_SYS_CHROOT`` in its current user namespace when\n+ * chrooted) and run in an ancestor active PID namespace. The child inherits\n+ * the caller's credentials and switches to the target user namespace.\n+ *\n+ * ``CLONE_INTO_ROOTNS`` may be combined with the following ``CLONE_*`` flags:\n+ *\n+ * - ``CLONE_VFORK``\n+ * - ``CLONE_PIDFD``\n+ * - ``CLONE_PIDFD_AUTOKILL``\n+ * - ``CLONE_AUTOREAP``\n+ * - ``CLONE_CLEAR_SIGHAND``\n+ * - ``CLONE_INTO_CGROUP``\n+ * - ``CLONE_NNP``\n+ *\n+ * Returns ``-EBADF`` if ``rootns`` is not an open file descriptor, ``-EINVAL``\n+ * for unsupported flags, invalid argument size, or non-``rootns`` file\n+ * descriptors, ``-ENOENT`` before ``\"/\"`` is installed, ``-EXDEV`` if the\n+ * caller's active PID namespace is not an ancestor, ``-EPERM`` without\n+ * required capabilities, ``-EBUSY`` if the PID\n+ * namespace already has an external init process, and ``-ESRCH`` once teardown\n+ * has started.\n+ */\n+int rootns_prepare_fork(struct kernel_clone_args *args)\n+{\n+\tstruct file *file __free(fput) = fget(args-\u003erootns_fd);\n+\tstruct path root __free(path_put) = {};\n+\tstruct pid_namespace *pid_ns;\n+\tbool bootstrapping = false;\n+\tstruct rootns *rootns;\n+\tint ret;\n+\n+\tif (!file)\n+\t\treturn -EBADF;\n+\tif (!is_rootns_file(file))\n+\t\treturn -EINVAL;\n+\n+\trootns = file-\u003eprivate_data;\n+\tif (!ns_capable(rootns-\u003euser_ns, CAP_SYS_ADMIN) ||\n+\t    !ns_capable(rootns-\u003euser_ns, CAP_SYS_CHROOT))\n+\t\treturn -EPERM;\n+\tif (current_chrooted() \u0026\u0026 !ns_capable(current_user_ns(), CAP_SYS_CHROOT))\n+\t\treturn -EPERM;\n+\n+\tpid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n+\tif (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))\n+\t\treturn -EXDEV;\n+\n+\tret = security_rootns_clone(rootns);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = mnt_ns_get_root(rootns-\u003ens-\u003emnt_ns, \u0026root);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tfor (;;) {\n+\t\tbool wait = false;\n+\n+\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n+\t\t\tswitch (rootns-\u003estate) {\n+\t\t\tcase ROOTNS_INIT:\n+\t\t\t\tif (READ_ONCE(pid_ns-\u003echild_reaper))\n+\t\t\t\t\treturn -EBUSY;\n+\t\t\t\tif (!(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n+\t\t\t\t\treturn -ESRCH;\n+\t\t\t\tWRITE_ONCE(rootns-\u003estate, ROOTNS_FORKING);\n+\t\t\t\tbootstrapping = true;\n+\t\t\t\tbreak;\n+\t\t\tcase ROOTNS_FORKING:\n+\t\t\t\twait = true;\n+\t\t\t\tbreak;\n+\t\t\tcase ROOTNS_RUNNING:\n+\t\t\t\tif (!(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n+\t\t\t\t\treturn -ESRCH;\n+\t\t\t\tbreak;\n+\t\t\tcase ROOTNS_DEAD:\n+\t\t\t\treturn -ESRCH;\n+\t\t\t}\n+\t\t}\n+\t\tif (!wait)\n+\t\t\tbreak;\n+\n+\t\tret = wait_event_killable(rootns-\u003ewaitq,\n+\t\t\t\t\t  READ_ONCE(rootns-\u003estate) != ROOTNS_FORKING);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\n+\targs-\u003erootns_file = no_free_ptr(file);\n+\targs-\u003erootns = rootns;\n+\targs-\u003erootns_bootstrapping = bootstrapping;\n+\treturn 0;\n+}\n+\n+int rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)\n+{\n+\tstruct file *file __free(fput) = args-\u003erootns_file;\n+\tstruct rootns *rootns = args-\u003erootns;\n+\tstruct pid_namespace *pid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n+\tint ret;\n+\n+\targs-\u003erootns_file = NULL;\n+\targs-\u003erootns = NULL;\n+\tif (!IS_ERR(p)) {\n+\t\tif (current-\u003ensproxy-\u003etime_ns != rootns-\u003ens-\u003etime_ns)\n+\t\t\ttimens_commit(p, rootns-\u003ens-\u003etime_ns);\n+\t\treturn 0;\n+\t}\n+\n+\tret = PTR_ERR(p);\n+\tif (args-\u003erootns_bootstrapping) {\n+\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n+\t\t\tif (rootns-\u003estate == ROOTNS_FORKING)\n+\t\t\t\tWRITE_ONCE(rootns-\u003estate, ROOTNS_INIT);\n+\t\t}\n+\t\twake_up_all(\u0026rootns-\u003ewaitq);\n+\t\tif (ret == -EINVAL \u0026\u0026 !args-\u003eset_tid_size)\n+\t\t\tret = -EBUSY;\n+\t}\n+\tif ((ret == -ENOMEM || ret == -EBUSY) \u0026\u0026\n+\t    !(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n+\t\treturn -ESRCH;\n+\n+\treturn ret;\n+}\ndiff --git a/kernel/sys_ni.c b/kernel/sys_ni.c\nindex c8be0abaa40778..9fba98f15a2069 100644\n--- a/kernel/sys_ni.c\n+++ b/kernel/sys_ni.c\n@@ -398,3 +398,6 @@ COND_SYSCALL(rseq_slice_yield);\n \n COND_SYSCALL(uretprobe);\n COND_SYSCALL(uprobe);\n+\n+/* kernel/rootns.c */\n+COND_SYSCALL(rootns);\ndiff --git a/kernel/user_namespace.c b/kernel/user_namespace.c\nindex cd748e1cbacef9..3bea8664719169 100644\n--- a/kernel/user_namespace.c\n+++ b/kernel/user_namespace.c\n@@ -1372,6 +1372,13 @@ static void userns_put(struct ns_common *ns)\n \tput_user_ns(to_user_ns(ns));\n }\n \n+int install_user_ns_cred(struct cred *cred, struct user_namespace *user_ns)\n+{\n+\tput_user_ns(cred-\u003euser_ns);\n+\tset_cred_user_ns(cred, get_user_ns(user_ns));\n+\treturn set_cred_ucounts(cred);\n+}\n+\n static int userns_install(struct nsset *nsset, struct ns_common *ns)\n {\n \tstruct user_namespace *user_ns = to_user_ns(ns);\n@@ -1397,10 +1404,7 @@ static int userns_install(struct nsset *nsset, struct ns_common *ns)\n \tif (!cred)\n \t\treturn -EINVAL;\n \n-\tput_user_ns(cred-\u003euser_ns);\n-\tset_cred_user_ns(cred, get_user_ns(user_ns));\n-\n-\tif (set_cred_ucounts(cred) \u003c 0)\n+\tif (install_user_ns_cred(cred, user_ns) \u003c 0)\n \t\treturn -EINVAL;\n \n \treturn 0;\ndiff --git a/scripts/syscall.tbl b/scripts/syscall.tbl\nindex 0ab5316051202e..b6d1b033f49ab2 100644\n--- a/scripts/syscall.tbl\n+++ b/scripts/syscall.tbl\n@@ -413,3 +413,4 @@\n 470\tcommon\tlistns\t\t\t\tsys_listns\n 471\tcommon\trseq_slice_yield\t\tsys_rseq_slice_yield\n 472\tcommon\tfchroot\t\t\t\tsys_fchroot\n+473\tcommon\trootns\t\t\t\tsys_rootns\ndiff --git a/security/lsm_init.c b/security/lsm_init.c\nindex 8d5ecea99c46b8..56b515b20812cb 100644\n--- a/security/lsm_init.c\n+++ b/security/lsm_init.c\n@@ -316,6 +316,9 @@ static void __init lsm_prepare(struct lsm_info *lsm)\n \tlsm_blob_size_update(\u0026blobs-\u003elbs_bpf_map, \u0026blob_sizes.lbs_bpf_map);\n \tlsm_blob_size_update(\u0026blobs-\u003elbs_bpf_prog, \u0026blob_sizes.lbs_bpf_prog);\n \tlsm_blob_size_update(\u0026blobs-\u003elbs_bpf_token, \u0026blob_sizes.lbs_bpf_token);\n+#ifdef CONFIG_ROOTNS\n+\tlsm_blob_size_update(\u0026blobs-\u003elbs_rootns, \u0026blob_sizes.lbs_rootns);\n+#endif\n }\n \n /**\n@@ -460,6 +463,9 @@ int __init security_init(void)\n \t\tlsm_pr(\"blob(bpf_map) size %d\\n\", blob_sizes.lbs_bpf_map);\n \t\tlsm_pr(\"blob(bpf_prog) size %d\\n\", blob_sizes.lbs_bpf_prog);\n \t\tlsm_pr(\"blob(bpf_token) size %d\\n\", blob_sizes.lbs_bpf_token);\n+#ifdef CONFIG_ROOTNS\n+\t\tlsm_pr(\"blob(rootns) size %d\\n\", blob_sizes.lbs_rootns);\n+#endif\n \t}\n \n \tif (blob_sizes.lbs_file)\ndiff --git a/security/security.c b/security/security.c\nindex 4727b8347fc4e2..919d4bb6370139 100644\n--- a/security/security.c\n+++ b/security/security.c\n@@ -30,6 +30,7 @@\n #include \u003clinux/overflow.h\u003e\n #include \u003clinux/perf_event.h\u003e\n #include \u003clinux/fs.h\u003e\n+#include \u003clinux/rootns.h\u003e\n #include \u003cnet/flow.h\u003e\n #include \u003cnet/sock.h\u003e\n \n@@ -395,6 +396,22 @@ static int lsm_ns_alloc(struct ns_common *ns)\n \treturn lsm_blob_alloc(\u0026ns-\u003ens_security, blob_sizes.lbs_ns, GFP_KERNEL);\n }\n \n+#ifdef CONFIG_ROOTNS\n+/**\n+ * lsm_rootns_alloc - allocate a composite rootns blob\n+ * @rootns: the rootns that needs a blob\n+ *\n+ * Allocate the rootns blob for all the modules\n+ *\n+ * Return: Returns 0, or -ENOMEM if memory can't be allocated.\n+ */\n+static int lsm_rootns_alloc(struct rootns *rootns)\n+{\n+\treturn lsm_blob_alloc(\u0026rootns-\u003esecurity, blob_sizes.lbs_rootns,\n+\t\t\t      GFP_KERNEL);\n+}\n+#endif /* CONFIG_ROOTNS */\n+\n /**\n  * lsm_fill_user_ctx - Fill a user space lsm_ctx structure\n  * @uctx: a userspace LSM context to be filled\n@@ -5795,3 +5812,72 @@ void security_initramfs_populated(void)\n {\n \tcall_void_hook(initramfs_populated);\n }\n+\n+#ifdef CONFIG_ROOTNS\n+/**\n+ * security_rootns_alloc() - Check creation of a new rootns and init LSM blob\n+ * @rootns: the new rootns\n+ * @flags: creation flags passed to rootns()\n+ *\n+ * Check whether a new rootns may be created and initialize its LSM security\n+ * blob.\n+ *\n+ * Return: Returns 0 on success, negative error code on failure.\n+ */\n+int security_rootns_alloc(struct rootns *rootns, unsigned int flags)\n+{\n+\tint rc;\n+\n+\trc = lsm_rootns_alloc(rootns);\n+\tif (unlikely(rc))\n+\t\treturn rc;\n+\n+\trc = call_int_hook(rootns_alloc, rootns, flags);\n+\tif (unlikely(rc))\n+\t\tsecurity_rootns_free(rootns);\n+\n+\treturn rc;\n+}\n+\n+/**\n+ * security_rootns_free() - Release LSM security data from a rootns\n+ * @rootns: the rootns being freed\n+ *\n+ * Release security data attached to @rootns before the structure is freed.\n+ */\n+void security_rootns_free(struct rootns *rootns)\n+{\n+\tcall_void_hook(rootns_free, rootns);\n+\tkfree(rootns-\u003esecurity);\n+\trootns-\u003esecurity = NULL;\n+}\n+\n+/**\n+ * security_rootns_clone() - Check permission to spawn a task into a rootns\n+ * @rootns: the target rootns\n+ *\n+ * Check permission before spawning a child process into @rootns via\n+ * clone3(CLONE_INTO_ROOTNS).\n+ *\n+ * Return: Returns 0 if permission is granted, negative error code on failure.\n+ */\n+int security_rootns_clone(struct rootns *rootns)\n+{\n+\treturn call_int_hook(rootns_clone, rootns);\n+}\n+\n+/**\n+ * security_rootns_kill() - Check permission to signal a rootns\n+ * @rootns: the target rootns\n+ * @sig: signal number to deliver (or 0 for permission check)\n+ *\n+ * Check permission before broadcasting @sig to member thread groups in @rootns\n+ * via ioctl(ROOTNS_KILL).\n+ *\n+ * Return: Returns 0 if permission is granted, negative error code on failure.\n+ */\n+int security_rootns_kill(struct rootns *rootns, int sig)\n+{\n+\treturn call_int_hook(rootns_kill, rootns, sig);\n+}\n+#endif /* CONFIG_ROOTNS */\ndiff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile\nindex 07c3719f8b04bf..7c44f93e57a475 100644\n--- a/tools/testing/selftests/Makefile\n+++ b/tools/testing/selftests/Makefile\n@@ -117,6 +117,7 @@ TARGETS += rdma\n TARGETS += resctrl\n TARGETS += riscv\n TARGETS += rlimits\n+TARGETS += rootns\n TARGETS += rseq\n TARGETS += rtc\n TARGETS += rust\ndiff --git a/tools/testing/selftests/rootns/Makefile b/tools/testing/selftests/rootns/Makefile\nnew file mode 100644\nindex 00000000000000..62629d112e12f3\n--- /dev/null\n+++ b/tools/testing/selftests/rootns/Makefile\n@@ -0,0 +1,5 @@\n+# SPDX-License-Identifier: GPL-2.0\n+include ../lib.mk\n+\n+TEST_PROGS := test_smoke.sh\n+TEST_PROGS_EXTENDED := rootns_cells.py rootns_test.py\ndiff --git a/tools/testing/selftests/rootns/config b/tools/testing/selftests/rootns/config\nnew file mode 100644\nindex 00000000000000..21b1aecc003b86\n--- /dev/null\n+++ b/tools/testing/selftests/rootns/config\n@@ -0,0 +1,10 @@\n+CONFIG_CGROUPS=y\n+CONFIG_IPC_NS=y\n+CONFIG_NET_NS=y\n+CONFIG_PID_NS=y\n+CONFIG_PROC_FS=y\n+CONFIG_ROOTNS=y\n+CONFIG_TIME_NS=y\n+CONFIG_TMPFS=y\n+CONFIG_USER_NS=y\n+CONFIG_UTS_NS=y\ndiff --git a/tools/testing/selftests/rootns/rootns_cells.py b/tools/testing/selftests/rootns/rootns_cells.py\nnew file mode 100755\nindex 00000000000000..b690ed71a5211c\n--- /dev/null\n+++ b/tools/testing/selftests/rootns/rootns_cells.py\n@@ -0,0 +1,1076 @@\n+#!/usr/bin/env python3\n+# SPDX-License-Identifier: GPL-2.0\n+#\n+# Copyright (C) 2026 Opinsys Oy\n+\n+from __future__ import annotations\n+\n+import argparse\n+from collections.abc import Callable, Mapping, Sequence\n+import ctypes\n+from dataclasses import asdict, dataclass, field\n+import errno\n+import json\n+import os\n+import platform\n+import selectors\n+import signal\n+import socket\n+import sys\n+from types import TracebackType\n+from typing import Any, Final, NoReturn\n+\n+ROOTNS_KILL_ON_CLOSE: Final[int] = 0x00000001\n+ROOTNS_CLOSE_ON_EXEC: Final[int] = 0x00000002\n+ROOTNS_ALL_FLAGS: Final[int] = 0x00000003\n+ROOTNS_IOCTL_MAGIC: Final[int] = 0xB9\n+\n+CLONE_NEWTIME: Final[int] = 0x00000080\n+CLONE_VM: Final[int] = 0x00000100\n+CLONE_FS: Final[int] = 0x00000200\n+CLONE_FILES: Final[int] = 0x00000400\n+CLONE_SIGHAND: Final[int] = 0x00000800\n+CLONE_PIDFD: Final[int] = 0x00001000\n+CLONE_VFORK: Final[int] = 0x00004000\n+CLONE_PARENT: Final[int] = 0x00008000\n+CLONE_THREAD: Final[int] = 0x00010000\n+CLONE_NEWNS: Final[int] = 0x00020000\n+CLONE_SYSVSEM: Final[int] = 0x00040000\n+CLONE_NEWCGROUP: Final[int] = 0x02000000\n+CLONE_NEWUTS: Final[int] = 0x04000000\n+CLONE_NEWIPC: Final[int] = 0x08000000\n+CLONE_NEWUSER: Final[int] = 0x10000000\n+CLONE_NEWPID: Final[int] = 0x20000000\n+CLONE_NEWNET: Final[int] = 0x40000000\n+\n+CLONE_CLEAR_SIGHAND: Final[int] = 1 \u003c\u003c 32\n+CLONE_INTO_CGROUP: Final[int] = 1 \u003c\u003c 33\n+CLONE_AUTOREAP: Final[int] = 1 \u003c\u003c 34\n+CLONE_NNP: Final[int] = 1 \u003c\u003c 35\n+CLONE_PIDFD_AUTOKILL: Final[int] = 1 \u003c\u003c 36\n+CLONE_EMPTY_MNTNS: Final[int] = 1 \u003c\u003c 37\n+CLONE_INTO_ROOTNS: Final[int] = 1 \u003c\u003c 38\n+\n+CLONE_ARGS_SIZE_VER2: Final[int] = 88\n+CLONE_ARGS_SIZE_VER3: Final[int] = 96\n+\n+AT_FDCWD: Final[int] = -100\n+AT_EMPTY_PATH: Final[int] = 0x1000\n+AT_RECURSIVE: Final[int] = 0x8000\n+MNT_DETACH: Final[int] = 2\n+MS_REC: Final[int] = 0x4000\n+MS_PRIVATE: Final[int] = 1 \u003c\u003c 18\n+\n+OPEN_TREE_CLONE: Final[int] = 1 \u003c\u003c 0\n+OPEN_TREE_CLOEXEC: Final[int] = os.O_CLOEXEC\n+\n+MOVE_MOUNT_F_EMPTY_PATH: Final[int] = 0x00000004\n+MOVE_MOUNT_T_EMPTY_PATH: Final[int] = 0x00000040\n+MOVE_MOUNT_T_MNTNS: Final[int] = 0x00000080\n+MOVE_MOUNT_SET_GROUP: Final[int] = 0x00000100\n+MOVE_MOUNT_BENEATH: Final[int] = 0x00000200\n+\n+FSOPEN_CLOEXEC: Final[int] = 0x00000001\n+FSMOUNT_CLOEXEC: Final[int] = 0x00000001\n+\n+FSCONFIG_SET_FLAG: Final[int] = 0\n+FSCONFIG_SET_STRING: Final[int] = 1\n+FSCONFIG_CMD_CREATE: Final[int] = 6\n+FSCONFIG_SET_ROOTNS: Final[int] = 9\n+\n+MOUNT_ATTR_RDONLY: Final[int] = 0x00000001\n+MOUNT_ATTR_NOSUID: Final[int] = 0x00000002\n+MOUNT_ATTR_NODEV: Final[int] = 0x00000004\n+\n+RESOLVE_IN_ROOT: Final[int] = 0x10\n+\n+PR_GET_DUMPABLE: Final[int] = 3\n+PR_SET_DUMPABLE: Final[int] = 4\n+PR_GET_NO_NEW_PRIVS: Final[int] = 39\n+\n+NSIO: Final[int] = 0xB7\n+\n+HOST_RUNTIME_ENTRIES: Final[tuple[str, ...]] = (\n+    \"usr\",\n+    \"bin\",\n+    \"sbin\",\n+    \"lib\",\n+    \"lib32\",\n+    \"lib64\",\n+    \"libx32\",\n+    \"etc\",\n+    \"opt\",\n+    \"nix\",\n+)\n+\n+_WIDE_IOC_ARCHS: Final[tuple[str, ...]] = (\n+    \"ppc\",\n+    \"ppc64\",\n+    \"ppc64le\",\n+    \"powerpc\",\n+    \"sparc\",\n+    \"sparc64\",\n+    \"alpha\",\n+)\n+\n+\n+def _is_wide_ioc_arch() -\u003e bool:\n+    mach = platform.machine().lower()\n+    return mach in _WIDE_IOC_ARCHS or mach.startswith(\"mips\")\n+\n+\n+def _ioc(direction: int, magic: int, nr: int, size: int) -\u003e int:\n+    sizebits = 13 if _is_wide_ioc_arch() else 14\n+    typeshift = 8\n+    sizeshift = 16\n+    dirshift = sizeshift + sizebits\n+    return (\n+        (direction \u003c\u003c dirshift)\n+        | (magic \u003c\u003c typeshift)\n+        | nr\n+        | (size \u003c\u003c sizeshift)\n+    )\n+\n+\n+def _io(magic: int, nr: int) -\u003e int:\n+    return _ioc(0, magic, nr, 0)\n+\n+\n+def _iowr(magic: int, nr: int, size: int) -\u003e int:\n+    rw = 6 if _is_wide_ioc_arch() else 3\n+    return _ioc(rw, magic, nr, size)\n+\n+\n+class RootnsWaitArgs(ctypes.Structure):\n+    flags: int\n+    status: int\n+    _fields_ = [\n+        (\"flags\", ctypes.c_uint32),\n+        (\"status\", ctypes.c_int32),\n+    ]\n+\n+\n+class CloneArgs(ctypes.Structure):\n+    flags: int\n+    pidfd: int\n+    child_tid: int\n+    parent_tid: int\n+    exit_signal: int\n+    stack: int\n+    stack_size: int\n+    tls: int\n+    set_tid: int\n+    set_tid_size: int\n+    cgroup: int\n+    rootns: int\n+    _fields_ = [\n+        (\"flags\", ctypes.c_uint64),\n+        (\"pidfd\", ctypes.c_uint64),\n+        (\"child_tid\", ctypes.c_uint64),\n+        (\"parent_tid\", ctypes.c_uint64),\n+        (\"exit_signal\", ctypes.c_uint64),\n+        (\"stack\", ctypes.c_uint64),\n+        (\"stack_size\", ctypes.c_uint64),\n+        (\"tls\", ctypes.c_uint64),\n+        (\"set_tid\", ctypes.c_uint64),\n+        (\"set_tid_size\", ctypes.c_uint64),\n+        (\"cgroup\", ctypes.c_uint64),\n+        (\"rootns\", ctypes.c_uint64),\n+    ]\n+\n+\n+class OpenHow(ctypes.Structure):\n+    flags: int\n+    mode: int\n+    resolve: int\n+    _fields_ = [\n+        (\"flags\", ctypes.c_uint64),\n+        (\"mode\", ctypes.c_uint64),\n+        (\"resolve\", ctypes.c_uint64),\n+    ]\n+\n+\n+ROOTNS_GET_NSFD: Final[int] = _io(ROOTNS_IOCTL_MAGIC, 0x01)\n+ROOTNS_WAIT: Final[int] = _iowr(\n+    ROOTNS_IOCTL_MAGIC, 0x02, ctypes.sizeof(RootnsWaitArgs)\n+)\n+ROOTNS_KILL: Final[int] = _io(ROOTNS_IOCTL_MAGIC, 0x03)\n+\n+NS_GET_USERNS: Final[int] = _io(NSIO, 0x01)\n+NS_GET_PARENT: Final[int] = _io(NSIO, 0x02)\n+NS_GET_NSTYPE: Final[int] = _io(NSIO, 0x03)\n+\n+\n+def _syscall_numbers() -\u003e dict[str, int]:\n+    mach = platform.machine().lower()\n+    if mach == \"alpha\":\n+        base = 110\n+    elif mach.startswith(\"mips\"):\n+        base = 5000 if ctypes.sizeof(ctypes.c_void_p) == 8 else 4000\n+    else:\n+        base = 0\n+\n+    nums: dict[str, int] = {\n+        \"open_tree\": base + 428,\n+        \"move_mount\": base + 429,\n+        \"fsopen\": base + 430,\n+        \"fsconfig\": base + 431,\n+        \"fsmount\": base + 432,\n+        \"pidfd_open\": base + 434,\n+        \"clone3\": base + 435,\n+        \"openat2\": base + 437,\n+        \"rootns\": base + 473,\n+    }\n+    legacy: dict[str, dict[str, int]] = {\n+        \"x86_64\": {\"pivot_root\": 155, \"umount2\": 166, \"execveat\": 322},\n+        \"i386\": {\"pivot_root\": 217, \"umount2\": 52, \"execveat\": 358},\n+        \"i686\": {\"pivot_root\": 217, \"umount2\": 52, \"execveat\": 358},\n+        \"aarch64\": {\"pivot_root\": 41, \"umount2\": 39, \"execveat\": 281},\n+        \"riscv64\": {\"pivot_root\": 41, \"umount2\": 39, \"execveat\": 281},\n+        \"loongarch64\": {\"pivot_root\": 41, \"umount2\": 39, \"execveat\": 281},\n+        \"s390x\": {\"pivot_root\": 217, \"umount2\": 52, \"execveat\": 354},\n+        \"ppc64le\": {\"pivot_root\": 203, \"umount2\": 52, \"execveat\": 362},\n+        \"ppc64\": {\"pivot_root\": 203, \"umount2\": 52, \"execveat\": 362},\n+        \"armv7l\": {\"pivot_root\": 218, \"umount2\": 52, \"execveat\": 387},\n+    }\n+    nums.update(legacy.get(mach, legacy[\"x86_64\"]))\n+    return nums\n+\n+\n+NR: Final[dict[str, int]] = _syscall_numbers()\n+LIBC: Final[ctypes.CDLL] = ctypes.CDLL(None, use_errno=True)\n+LIBC.syscall.restype = ctypes.c_long\n+\n+\n+@dataclass(frozen=True)\n+class WaitResult:\n+    pid: int\n+    status: int = 0\n+\n+    @property\n+    def exit_code(self) -\u003e int | None:\n+        if self.pid \u003c= 0:\n+            return None\n+        return os.waitstatus_to_exitcode(self.status)\n+\n+\n+@dataclass(frozen=True)\n+class CellInfo:\n+    name: str\n+    state: str\n+    init_pid: int | None = None\n+    exit_code: int | None = None\n+\n+\n+@dataclass(frozen=True)\n+class SpawnInfo:\n+    pid: int\n+    state: str\n+\n+\n+def _os_err() -\u003e NoReturn:\n+    err = ctypes.get_errno()\n+    raise OSError(err, os.strerror(err))\n+\n+\n+def _cstr(val: str | bytes) -\u003e bytes:\n+    if isinstance(val, bytes):\n+        return val\n+    return os.fsencode(val)\n+\n+\n+def syscall(nr: int, *args: Any) -\u003e int:\n+    ret: int = LIBC.syscall(ctypes.c_long(nr), *args)\n+    if ret \u003c 0:\n+        _os_err()\n+    return int(ret)\n+\n+\n+def raw_ioctl(fd: int, cmd: int, arg: int = 0) -\u003e int:\n+    ret: int = LIBC.ioctl(\n+        ctypes.c_int(fd), ctypes.c_ulong(cmd), ctypes.c_ulong(arg)\n+    )\n+    if ret \u003c 0:\n+        _os_err()\n+    return int(ret)\n+\n+\n+def rootns(\n+    flags: int = ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC,\n+) -\u003e int:\n+    return syscall(NR[\"rootns\"], ctypes.c_uint(flags))\n+\n+\n+def rootns_get_nsfd(cfd: int, nstype: int) -\u003e int:\n+    return raw_ioctl(cfd, ROOTNS_GET_NSFD, nstype)\n+\n+\n+def rootns_wait(cfd: int, flags: int = 0) -\u003e WaitResult:\n+    args = RootnsWaitArgs(flags=flags, status=0)\n+    pid = raw_ioctl(cfd, ROOTNS_WAIT, ctypes.addressof(args))\n+    return WaitResult(pid=pid, status=int(args.status))\n+\n+\n+def rootns_kill(cfd: int, sig: int) -\u003e None:\n+    mask = (1 \u003c\u003c (ctypes.sizeof(ctypes.c_ulong) * 8)) - 1\n+    raw_ioctl(cfd, ROOTNS_KILL, sig \u0026 mask)\n+\n+\n+def fsopen(fsname: str | bytes, flags: int = FSOPEN_CLOEXEC) -\u003e int:\n+    return syscall(\n+        NR[\"fsopen\"], ctypes.c_char_p(_cstr(fsname)), ctypes.c_uint(flags)\n+    )\n+\n+\n+def fsconfig(\n+    fsfd: int,\n+    cmd: int,\n+    key: str | bytes | None = None,\n+    value: str | bytes | None = None,\n+    aux: int = 0,\n+) -\u003e None:\n+    k_ptr = (\n+        ctypes.c_char_p(_cstr(key)) if key is not None else ctypes.c_void_p(0)\n+    )\n+    v_ptr = (\n+        ctypes.c_char_p(_cstr(value))\n+        if value is not None\n+        else ctypes.c_void_p(0)\n+    )\n+    syscall(\n+        NR[\"fsconfig\"],\n+        ctypes.c_int(fsfd),\n+        ctypes.c_uint(cmd),\n+        k_ptr,\n+        v_ptr,\n+        ctypes.c_int(aux),\n+    )\n+\n+\n+def fsmount(\n+    fsfd: int, flags: int = FSMOUNT_CLOEXEC, attr_flags: int = 0\n+) -\u003e int:\n+    return syscall(\n+        NR[\"fsmount\"],\n+        ctypes.c_int(fsfd),\n+        ctypes.c_uint(flags),\n+        ctypes.c_uint(attr_flags),\n+    )\n+\n+\n+def open_tree(dfd: int, path: str | bytes, flags: int) -\u003e int:\n+    return syscall(\n+        NR[\"open_tree\"],\n+        ctypes.c_int(dfd),\n+        ctypes.c_char_p(_cstr(path)),\n+        ctypes.c_uint(flags),\n+    )\n+\n+\n+def move_mount(\n+    from_dfd: int,\n+    from_path: str | bytes,\n+    to_dfd: int,\n+    to_path: str | bytes,\n+    flags: int,\n+) -\u003e None:\n+    syscall(\n+        NR[\"move_mount\"],\n+        ctypes.c_int(from_dfd),\n+        ctypes.c_char_p(_cstr(from_path)),\n+        ctypes.c_int(to_dfd),\n+        ctypes.c_char_p(_cstr(to_path)),\n+        ctypes.c_uint(flags),\n+    )\n+\n+\n+def openat2(\n+    dfd: int,\n+    path: str | bytes,\n+    flags: int,\n+    mode: int = 0,\n+    resolve: int = 0,\n+) -\u003e int:\n+    how = OpenHow(flags=flags, mode=mode, resolve=resolve)\n+    return syscall(\n+        NR[\"openat2\"],\n+        ctypes.c_int(dfd),\n+        ctypes.c_char_p(_cstr(path)),\n+        ctypes.byref(how),\n+        ctypes.c_size_t(ctypes.sizeof(how)),\n+    )\n+\n+\n+def execveat(\n+    dfd: int,\n+    path: str | bytes,\n+    argv: Sequence[str],\n+    envp: Mapping[str, str] | Sequence[str] | None = None,\n+    flags: int = 0,\n+) -\u003e NoReturn:\n+    c_argv = (ctypes.c_char_p * (len(argv) + 1))(\n+        *[_cstr(a) for a in argv], None\n+    )\n+    if envp is None:\n+        env_items = [f\"{k}={v}\" for k, v in os.environ.items()]\n+    elif isinstance(envp, Mapping):\n+        env_items = [f\"{k}={v}\" for k, v in envp.items()]\n+    else:\n+        env_items = list(envp)\n+    c_envp = (ctypes.c_char_p * (len(env_items) + 1))(\n+        *[_cstr(e) for e in env_items], None\n+    )\n+    syscall(\n+        NR[\"execveat\"],\n+        ctypes.c_int(dfd),\n+        ctypes.c_char_p(_cstr(path)),\n+        c_argv,\n+        c_envp,\n+        ctypes.c_int(flags),\n+    )\n+    _os_err()\n+\n+\n+def pidfd_open(pid: int, flags: int = 0) -\u003e int:\n+    return syscall(NR[\"pidfd_open\"], ctypes.c_int(pid), ctypes.c_uint(flags))\n+\n+\n+def pivot_root(new_root: str | bytes, put_old: str | bytes) -\u003e None:\n+    syscall(\n+        NR[\"pivot_root\"],\n+        ctypes.c_char_p(_cstr(new_root)),\n+        ctypes.c_char_p(_cstr(put_old)),\n+    )\n+\n+\n+def umount2(target: str | bytes, flags: int = 0) -\u003e None:\n+    syscall(NR[\"umount2\"], ctypes.c_char_p(_cstr(target)), ctypes.c_int(flags))\n+\n+\n+def make_mount_private(target: str | bytes = \"/\") -\u003e None:\n+    ret: int = LIBC.mount(\n+        ctypes.c_char_p(b\"none\"),\n+        ctypes.c_char_p(_cstr(target)),\n+        ctypes.c_void_p(0),\n+        ctypes.c_ulong(MS_REC | MS_PRIVATE),\n+        ctypes.c_void_p(0),\n+    )\n+    if ret \u003c 0:\n+        _os_err()\n+\n+\n+def setns(fd: int, nstype: int = 0) -\u003e None:\n+    ret: int = LIBC.setns(ctypes.c_int(fd), ctypes.c_int(nstype))\n+    if ret \u003c 0:\n+        _os_err()\n+\n+\n+def unshare(flags: int) -\u003e None:\n+    ret: int = LIBC.unshare(ctypes.c_int(flags))\n+    if ret \u003c 0:\n+        _os_err()\n+\n+\n+def setgroups_empty() -\u003e None:\n+    ret: int = LIBC.setgroups(ctypes.c_size_t(0), ctypes.c_void_p(0))\n+    if ret \u003c 0:\n+        _os_err()\n+\n+\n+def prctl(\n+    option: int,\n+    arg2: int = 0,\n+    arg3: int = 0,\n+    arg4: int = 0,\n+    arg5: int = 0,\n+) -\u003e int:\n+    ret: int = LIBC.prctl(\n+        ctypes.c_int(option),\n+        ctypes.c_ulong(arg2),\n+        ctypes.c_ulong(arg3),\n+        ctypes.c_ulong(arg4),\n+        ctypes.c_ulong(arg5),\n+    )\n+    if ret \u003c 0:\n+        _os_err()\n+    return int(ret)\n+\n+\n+def clone3_raw(args: CloneArgs, size: int | None = None) -\u003e int:\n+    actual_size = ctypes.sizeof(args) if size is None else size\n+    sys.stdout.flush()\n+    sys.stderr.flush()\n+    return syscall(\n+        NR[\"clone3\"], ctypes.byref(args), ctypes.c_size_t(actual_size)\n+    )\n+\n+\n+def clone_into_rootns(\n+    cfd: int,\n+    extra_flags: int = 0,\n+    exit_signal: int = int(signal.SIGCHLD),\n+) -\u003e tuple[int, int]:\n+    pidfd_cell = ctypes.c_int(-1)\n+    args = CloneArgs()\n+    args.flags = CLONE_INTO_ROOTNS | extra_flags\n+    args.exit_signal = exit_signal\n+    args.rootns = cfd \u0026 0xFFFFFFFFFFFFFFFF\n+    if extra_flags \u0026 CLONE_PIDFD:\n+        args.pidfd = ctypes.addressof(pidfd_cell)\n+    pid = clone3_raw(args)\n+    return pid, int(pidfd_cell.value)\n+\n+\n+def run_in_rootns(\n+    cfd: int,\n+    fn: Callable[[], int | None],\n+    extra_flags: int = 0,\n+) -\u003e int:\n+    pid, _ = clone_into_rootns(cfd, extra_flags=extra_flags)\n+    if pid == 0:\n+        try:\n+            os.close(cfd)\n+            rc = fn()\n+            os._exit(0 if rc is None else int(rc))\n+        except BaseException:\n+            os._exit(126)\n+    return pid\n+\n+\n+def make_rootns_mount(\n+    cfd: int,\n+    fstype: str,\n+    attr_flags: int = 0,\n+    options: Mapping[str, str | None] | None = None,\n+) -\u003e int:\n+    fsfd = fsopen(fstype, FSOPEN_CLOEXEC)\n+    try:\n+        fsconfig(fsfd, FSCONFIG_SET_ROOTNS, aux=cfd)\n+        if options:\n+            for k, v in options.items():\n+                if v is None:\n+                    fsconfig(fsfd, FSCONFIG_SET_FLAG, key=k)\n+                else:\n+                    fsconfig(fsfd, FSCONFIG_SET_STRING, key=k, value=str(v))\n+        fsconfig(fsfd, FSCONFIG_CMD_CREATE)\n+        return fsmount(fsfd, FSMOUNT_CLOEXEC, attr_flags)\n+    finally:\n+        os.close(fsfd)\n+\n+\n+@dataclass\n+class Cell:\n+    name: str\n+    flags: int = ROOTNS_KILL_ON_CLOSE | ROOTNS_CLOSE_ON_EXEC\n+    cfd: int = field(init=False, default=-1)\n+    mntns_fd: int = field(init=False, default=-1)\n+    root_dfd: int = field(init=False, default=-1)\n+    init_pid: int | None = field(init=False, default=None)\n+    exit_status: int | None = field(init=False, default=None)\n+\n+    def __post_init__(self) -\u003e None:\n+        self.cfd = rootns(self.flags)\n+        self.mntns_fd = rootns_get_nsfd(self.cfd, CLONE_NEWNS)\n+\n+    def __enter__(self) -\u003e Cell:\n+        return self\n+\n+    def __exit__(\n+        self,\n+        exc_type: type[BaseException] | None,\n+        exc: BaseException | None,\n+        tb: TracebackType | None,\n+    ) -\u003e None:\n+        self.close()\n+\n+    def setup_rootfs(\n+        self,\n+        dirs: Sequence[str] = (\"proc\", \"tmp\", \"mnt\"),\n+        mount_procfs: bool = True,\n+        host_runtime: bool = False,\n+    ) -\u003e None:\n+        rootfd = make_rootns_mount(self.cfd, \"tmpfs\")\n+        bind_dirs: list[str] = []\n+        try:\n+            for d in dirs:\n+                os.mkdir(d, 0o755, dir_fd=rootfd)\n+            if host_runtime:\n+                for entry in HOST_RUNTIME_ENTRIES:\n+                    host_path = f\"/{entry}\"\n+                    if os.path.islink(host_path):\n+                        os.symlink(\n+                            os.readlink(host_path), entry, dir_fd=rootfd\n+                        )\n+                    elif os.path.isdir(host_path):\n+                        os.mkdir(entry, 0o755, dir_fd=rootfd)\n+                        bind_dirs.append(entry)\n+            move_mount(\n+                rootfd,\n+                \"\",\n+                self.mntns_fd,\n+                \"/\",\n+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,\n+            )\n+            self.root_dfd = rootfd\n+            rootfd = -1\n+        finally:\n+            if rootfd \u003e= 0:\n+                os.close(rootfd)\n+        for entry in bind_dirs:\n+            self.bind_mount(f\"/{entry}\", entry)\n+        if mount_procfs and \"proc\" in dirs:\n+            self.mount_fs(\"proc\", \"proc\")\n+\n+    def mount_fs(\n+        self,\n+        fstype: str,\n+        target: str,\n+        attr_flags: int = 0,\n+        options: Mapping[str, str | None] | None = None,\n+    ) -\u003e None:\n+        mfd = make_rootns_mount(\n+            self.cfd, fstype, attr_flags=attr_flags, options=options\n+        )\n+        try:\n+            move_mount(\n+                mfd,\n+                \"\",\n+                self.mntns_fd,\n+                target.lstrip(\"/\"),\n+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,\n+            )\n+        finally:\n+            os.close(mfd)\n+\n+    def bind_mount(self, host_src: str, target: str) -\u003e None:\n+        mfd = open_tree(\n+            AT_FDCWD,\n+            host_src,\n+            OPEN_TREE_CLONE | AT_RECURSIVE | OPEN_TREE_CLOEXEC,\n+        )\n+        try:\n+            move_mount(\n+                mfd,\n+                \"\",\n+                self.mntns_fd,\n+                target.lstrip(\"/\"),\n+                MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_MNTNS,\n+            )\n+        finally:\n+            os.close(mfd)\n+\n+    def spawn(\n+        self,\n+        argv: Sequence[str],\n+        env: Mapping[str, str] | None = None,\n+        resolve_in_root: bool = True,\n+    ) -\u003e int:\n+        bin_fd = -1\n+        if resolve_in_root and self.root_dfd \u003e= 0:\n+            bin_fd = openat2(\n+                self.root_dfd,\n+                argv[0],\n+                os.O_RDONLY | os.O_CLOEXEC,\n+                resolve=RESOLVE_IN_ROOT,\n+            )\n+        try:\n+            pid, _ = clone_into_rootns(\n+                self.cfd, extra_flags=CLONE_AUTOREAP, exit_signal=0\n+            )\n+            if pid == 0:\n+                try:\n+                    os.close(self.cfd)\n+                    os.close(self.mntns_fd)\n+                    if self.root_dfd \u003e= 0:\n+                        os.close(self.root_dfd)\n+                    if bin_fd \u003e= 0:\n+                        execveat(bin_fd, \"\", argv, env, AT_EMPTY_PATH)\n+                    if env is None:\n+                        os.execv(argv[0], list(argv))\n+                    else:\n+                        os.execve(argv[0], list(argv), dict(env))\n+                except BaseException:\n+                    os._exit(127)\n+            if self.init_pid is None:\n+                self.init_pid = pid\n+            return pid\n+        finally:\n+            if bin_fd \u003e= 0:\n+                os.close(bin_fd)\n+\n+    def kill(self, sig: int = int(signal.SIGTERM)) -\u003e None:\n+        rootns_kill(self.cfd, sig)\n+\n+    def wait(self, nohang: bool = False) -\u003e WaitResult:\n+        res = rootns_wait(self.cfd, os.WNOHANG if nohang else 0)\n+        if res.pid \u003e 0:\n+            self.exit_status = res.status\n+        return res\n+\n+    @property\n+    def status_str(self) -\u003e str:\n+        if self.init_pid is None:\n+            return \"created\"\n+        if self.exit_status is None:\n+            return \"running\"\n+        return \"exited\"\n+\n+    def info(self) -\u003e CellInfo:\n+        code = (\n+            os.waitstatus_to_exitcode(self.exit_status)\n+            if self.exit_status is not None\n+            else None\n+        )\n+        return CellInfo(\n+            name=self.name,\n+            state=self.status_str,\n+            init_pid=self.init_pid,\n+            exit_code=code,\n+        )\n+\n+    def close(self) -\u003e None:\n+        for attr in (\"root_dfd\", \"mntns_fd\", \"cfd\"):\n+            fd: int = getattr(self, attr, -1)\n+            if fd \u003e= 0:\n+                try:\n+                    os.close(fd)\n+                except OSError:\n+                    pass\n+                setattr(self, attr, -1)\n+\n+\n+class CellService:\n+    def __init__(self, sock_path: str) -\u003e None:\n+        self.sock_path = sock_path\n+        self.sel = selectors.DefaultSelector()\n+        self.cells: dict[str, Cell] = {}\n+        self.running = True\n+        if os.path.exists(sock_path):\n+            os.unlink(sock_path)\n+        self.srv = socket.socket(\n+            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC\n+        )\n+        self.srv.bind(sock_path)\n+        self.srv.listen(16)\n+        self.srv.setblocking(False)\n+        self.sel.register(self.srv, selectors.EVENT_READ, self._on_accept)\n+\n+    def _reap_children(self) -\u003e None:\n+        while True:\n+            try:\n+                pid, _ = os.waitpid(-1, os.WNOHANG)\n+                if pid == 0:\n+                    break\n+            except ChildProcessError:\n+                break\n+\n+    def _on_cell_event(self, cell: Cell) -\u003e None:\n+        try:\n+            res = cell.wait(nohang=True)\n+            if res.pid \u003e 0:\n+                try:\n+                    self.sel.unregister(cell.cfd)\n+                except KeyError:\n+                    pass\n+        except OSError:\n+            pass\n+        self._reap_children()\n+\n+    def _on_accept(self) -\u003e None:\n+        conn, _ = self.srv.accept()\n+        with conn:\n+            data = b\"\"\n+            while not data.endswith(b\"\\n\"):\n+                chunk = conn.recv(4096)\n+                if not chunk:\n+                    break\n+                data += chunk\n+            if not data:\n+                return\n+            try:\n+                req: dict[str, Any] = json.loads(data.decode(\"utf-8\"))\n+                resp: dict[str, Any] = {\n+                    \"ok\": True,\n+                    \"result\": self._dispatch(req),\n+                }\n+            except Exception as exc:\n+                resp = {\n+                    \"ok\": False,\n+                    \"error\": str(exc),\n+                    \"errno\": getattr(exc, \"errno\", None),\n+                }\n+            conn.sendall((json.dumps(resp) + \"\\n\").encode(\"utf-8\"))\n+\n+    def _dispatch(self, req: Mapping[str, Any]) -\u003e Any:\n+        op = str(req[\"op\"])\n+        if op == \"ping\":\n+            return \"pong\"\n+        if op == \"shutdown\":\n+            self.running = False\n+            return \"bye\"\n+        if op == \"list\":\n+            self._reap_children()\n+            return [asdict(c.info()) for c in self.cells.values()]\n+\n+        name = str(req[\"name\"])\n+        if op == \"create\":\n+            if name in self.cells:\n+                raise OSError(errno.EEXIST, f\"cell {name} already exists\")\n+            cell = Cell(name)\n+            try:\n+                host_runtime = req.get(\"mode\", \"host\") == \"host\"\n+                cell.setup_rootfs(\n+                    mount_procfs=bool(req.get(\"proc\", True)),\n+                    host_runtime=host_runtime,\n+                )\n+            except Exception:\n+                cell.close()\n+                raise\n+            self.cells[name] = cell\n+            self.sel.register(\n+                cell.cfd,\n+                selectors.EVENT_READ,\n+                lambda c=cell: self._on_cell_event(c),\n+            )\n+            return asdict(cell.info())\n+\n+        cell_opt = self.cells.get(name)\n+        if cell_opt is None:\n+            raise OSError(errno.ENOENT, f\"unknown cell {name}\")\n+        cell = cell_opt\n+\n+        if op in (\"start\", \"exec\"):\n+            pid = cell.spawn(\n+                list(req[\"argv\"]),\n+                resolve_in_root=bool(req.get(\"resolve_in_root\", True)),\n+            )\n+            return asdict(SpawnInfo(pid=pid, state=cell.status_str))\n+        if op == \"mount\":\n+            if req.get(\"bind\"):\n+                cell.bind_mount(str(req[\"source\"]), str(req[\"target\"]))\n+            else:\n+                cell.mount_fs(\n+                    str(req[\"source\"]),\n+                    str(req[\"target\"]),\n+                    options=req.get(\"options\"),\n+                )\n+            return str(req[\"target\"])\n+        if op == \"kill\":\n+            cell.kill(int(req.get(\"sig\", int(signal.SIGTERM))))\n+            return name\n+        if op == \"wait\":\n+            res = cell.wait(nohang=bool(req.get(\"nohang\", False)))\n+            self._reap_children()\n+            return asdict(res)\n+        if op == \"destroy\":\n+            try:\n+                self.sel.unregister(cell.cfd)\n+            except KeyError:\n+                pass\n+            cell.close()\n+            del self.cells[name]\n+            self._reap_children()\n+            return name\n+        raise ValueError(f\"unsupported op {op}\")\n+\n+    def serve_forever(self) -\u003e None:\n+        try:\n+            while self.running:\n+                for key, _ in self.sel.select(timeout=0.2):\n+                    cb: Callable[[], None] = key.data\n+                    cb()\n+                self._reap_children()\n+        finally:\n+            self.close()\n+\n+    def close(self) -\u003e None:\n+        for cell in list(self.cells.values()):\n+            try:\n+                self.sel.unregister(cell.cfd)\n+            except KeyError:\n+                pass\n+            cell.close()\n+        self.cells.clear()\n+        try:\n+            self.sel.unregister(self.srv)\n+        except KeyError:\n+            pass\n+        self.srv.close()\n+        self.sel.close()\n+        if os.path.exists(self.sock_path):\n+            os.unlink(self.sock_path)\n+        self._reap_children()\n+\n+\n+@dataclass(frozen=True)\n+class CellClient:\n+    sock_path: str\n+\n+    def call(self, **req: Any) -\u003e Any:\n+        with socket.socket(\n+            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_CLOEXEC\n+        ) as s:\n+            s.connect(self.sock_path)\n+            s.sendall((json.dumps(req) + \"\\n\").encode(\"utf-8\"))\n+            data = b\"\"\n+            while not data.endswith(b\"\\n\"):\n+                chunk = s.recv(4096)\n+                if not chunk:\n+                    break\n+                data += chunk\n+        resp: dict[str, Any] = json.loads(data.decode(\"utf-8\"))\n+        if not resp[\"ok\"]:\n+            err = resp.get(\"errno\")\n+            if err is not None:\n+                raise OSError(int(err), str(resp[\"error\"]))\n+            raise RuntimeError(str(resp[\"error\"]))\n+        return resp[\"result\"]\n+\n+    def ping(self) -\u003e str:\n+        return str(self.call(op=\"ping\"))\n+\n+    def shutdown(self) -\u003e str:\n+        return str(self.call(op=\"shutdown\"))\n+\n+    def list_cells(self) -\u003e list[CellInfo]:\n+        items: list[dict[str, Any]] = self.call(op=\"list\")\n+        return [CellInfo(**item) for item in items]\n+\n+    def create(\n+        self, name: str, mode: str = \"host\", proc: bool = True\n+    ) -\u003e CellInfo:\n+        data: dict[str, Any] = self.call(\n+            op=\"create\", name=name, mode=mode, proc=proc\n+        )\n+        return CellInfo(**data)\n+\n+    def start(\n+        self,\n+        name: str,\n+        argv: Sequence[str],\n+        resolve_in_root: bool = True,\n+    ) -\u003e SpawnInfo:\n+        data: dict[str, Any] = self.call(\n+            op=\"start\",\n+            name=name,\n+            argv=list(argv),\n+            resolve_in_root=resolve_in_root,\n+        )\n+        return SpawnInfo(**data)\n+\n+    def exec_cmd(\n+        self,\n+        name: str,\n+        argv: Sequence[str],\n+        resolve_in_root: bool = True,\n+    ) -\u003e SpawnInfo:\n+        data: dict[str, Any] = self.call(\n+            op=\"exec\",\n+            name=name,\n+            argv=list(argv),\n+            resolve_in_root=resolve_in_root,\n+        )\n+        return SpawnInfo(**data)\n+\n+    def mount(\n+        self,\n+        name: str,\n+        source: str,\n+        target: str,\n+        bind: bool = False,\n+        options: Mapping[str, str | None] | None = None,\n+    ) -\u003e str:\n+        return str(\n+            self.call(\n+                op=\"mount\",\n+                name=name,\n+                source=source,\n+                target=target,\n+                bind=bind,\n+                options=dict(options) if options is not None else None,\n+            )\n+        )\n+\n+    def kill(self, name: str, sig: int = int(signal.SIGTERM)) -\u003e str:\n+        return str(self.call(op=\"kill\", name=name, sig=sig))\n+\n+    def wait(self, name: str, nohang: bool = False) -\u003e WaitResult:\n+        data: dict[str, Any] = self.call(op=\"wait\", name=name, nohang=nohang)\n+        return WaitResult(pid=int(data[\"pid\"]), status=int(data[\"status\"]))\n+\n+    def destroy(self, name: str) -\u003e str:\n+        return str(self.call(op=\"destroy\", name=name))\n+\n+\n+def _cli() -\u003e None:\n+    parser = argparse.ArgumentParser()\n+    parser.add_argument(\"--sock\", default=\"/tmp/rootns-cells.sock\")\n+    sub = parser.add_subparsers(dest=\"cmd\", required=True)\n+    sub.add_parser(\"daemon\")\n+    sub.add_parser(\"ps\")\n+    sub.add_parser(\"shutdown\")\n+\n+    p_create = sub.add_parser(\"create\")\n+    p_create.add_argument(\"name\")\n+    p_create.add_argument(\"--mode\", choices=(\"host\", \"tmpfs\"), default=\"host\")\n+\n+    for cname in (\"start\", \"exec\"):\n+        p_run = sub.add_parser(cname)\n+        p_run.add_argument(\"name\")\n+        p_run.add_argument(\"argv\", nargs=argparse.REMAINDER)\n+\n+    p_mnt = sub.add_parser(\"mount\")\n+    p_mnt.add_argument(\"name\")\n+    p_mnt.add_argument(\"source\")\n+    p_mnt.add_argument(\"target\")\n+    p_mnt.add_argument(\"--bind\", action=\"store_true\")\n+\n+    p_kill = sub.add_parser(\"kill\")\n+    p_kill.add_argument(\"name\")\n+    p_kill.add_argument(\"-s\", \"--sig\", type=int, default=int(signal.SIGTERM))\n+\n+    p_wait = sub.add_parser(\"wait\")\n+    p_wait.add_argument(\"name\")\n+\n+    p_rm = sub.add_parser(\"destroy\")\n+    p_rm.add_argument(\"name\")\n+\n+    args = parser.parse_args()\n+    if args.cmd == \"daemon\":\n+        CellService(args.sock).serve_forever()\n+        return\n+\n+    client = CellClient(args.sock)\n+    if args.cmd == \"ps\":\n+        print(json.dumps([asdict(c) for c in client.list_cells()], indent=2))\n+    elif args.cmd == \"shutdown\":\n+        print(json.dumps(client.shutdown()))\n+    elif args.cmd == \"create\":\n+        print(json.dumps(asdict(client.create(args.name, mode=args.mode))))\n+    elif args.cmd in (\"start\", \"exec\"):\n+        argv = (\n+            args.argv[1:]\n+            if args.argv and args.argv[0] == \"--\"\n+            else list(args.argv)\n+        )\n+        fn = client.start if args.cmd == \"start\" else client.exec_cmd\n+        print(json.dumps(asdict(fn(args.name, argv))))\n+    elif args.cmd == \"mount\":\n+        print(\n+            json.dumps(\n+                client.mount(\n+                    args.name, args.source, args.target, bind=args.bind\n+                )\n+            )\n+        )\n+    elif args.cmd == \"kill\":\n+        print(json.dumps(client.kill(args.name, args.sig)))\n+    elif args.cmd == \"wait\":\n+        res = client.wait(args.name)\n+        print(json.dumps({\"pid\": res.pid, \"exit_code\": res.exit_code}))\n+    elif args.cmd == \"destroy\":\n+        print(json.dumps(client.destroy(args.name)))\n+\n+\n+if __name__ == \"__main__\":\n+    _cli()\ndiff --git a/tools/testing/selftests/rootns/rootns_test.py b/tools/testing/selftests/rootns/rootns_test.py\nnew file mode 100755\nindex 00000000000000..7594b7a40c0cfe\n--- /dev/null\n+++ b/tools/testing/selftests/rootns/rootns_test.py\n@@ -0,0 +1,1161 @@\n+#!/usr/bin/env python3\n+# SPDX-License-Identifier: GPL-2.0\n+#\n+# Copyright (C) 2026 Opinsys Oy\n+\n+from __future__ import annotations\n+\n+import ctypes\n+from dataclasses import dataclass\n+import errno\n+import os\n+import select\n+import shutil\n+import signal\n+import socket\n+import sys\n+import tempfile\n+import time\n+from typing import Final\n+import unittest\n+\n+import rootns_cells as rc\n+\n+PYTHON_BIN: Final[str] = os.path.realpath(sys.executable)\n+SKIP_EXIT: Final[int] = 77\n+SKIP_ERRNOS: Final[tuple[int, ...]] = (\n+    errno.ENOSYS,\n+    errno.EPERM,\n+    errno.EACCES,\n+    errno.EINVAL,\n+    errno.ENOSPC,\n+)\n+\n+\n+@dataclass(frozen=True)\n+class Payload:\n+    code: str\n+\n+    def argv(self) -\u003e list[str]:\n+        return [PYTHON_BIN, \"-S\", \"-c\", self.code]\n+\n+\n+WAIT_MOUNT_PAYLOAD: Final[Payload] = Payload(\n+    \"\"\"\\\n+import os\n+import sys\n+import time\n+\n+if os.getpid() != 1:\n+    sys.exit(1)\n+deadline = time.monotonic() + 5.0\n+while time.monotonic() \u003c deadline:\n+    if os.path.ismount(\"/mnt\") and os.path.exists(\"/mnt/done\"):\n+        with open(\"/mnt/done\", \"rb\") as f:\n+            sys.exit(0 if f.read() == b\"ok\\\\n\" else 2)\n+    time.sleep(0.02)\n+sys.exit(3)\n+\"\"\"\n+)\n+\n+WRITE_MOUNT_PAYLOAD: Final[Payload] = Payload(\n+    \"\"\"\\\n+import os\n+import sys\n+\n+if not os.path.ismount(\"/mnt\"):\n+    sys.exit(1)\n+with open(\"/mnt/done.tmp\", \"wb\") as f:\n+    f.write(b\"ok\\\\n\")\n+os.replace(\"/mnt/done.tmp\", \"/mnt/done\")\n+\"\"\"\n+)\n+\n+PAUSE_PAYLOAD: Final[Payload] = Payload(\n+    \"\"\"\\\n+import signal\n+\n+signal.pause()\n+\"\"\"\n+)\n+\n+\n+@dataclass(frozen=True)\n+class ProbeResult:\n+    supported: bool\n+    reason: str = \"\"\n+\n+\n+@dataclass\n+class SyncPipe:\n+    r_fd: int\n+    w_fd: int\n+\n+    @classmethod\n+    def create(cls) -\u003e SyncPipe:\n+        r_fd, w_fd = os.pipe2(os.O_CLOEXEC)\n+        return cls(r_fd=r_fd, w_fd=w_fd)\n+\n+    def close_read(self) -\u003e None:\n+        if self.r_fd \u003e= 0:\n+            os.close(self.r_fd)\n+            self.r_fd = -1\n+\n+    def close_write(self) -\u003e None:\n+        if self.w_fd \u003e= 0:\n+            os.close(self.w_fd)\n+            self.w_fd = -1\n+\n+    def close(self) -\u003e None:\n+        self.close_read()\n+        self.close_write()\n+\n+    def read_bytes(self, n: int = 1) -\u003e bytes:\n+        return os.read(self.r_fd, n)\n+\n+    def write_bytes(self, data: bytes = b\"1\") -\u003e None:\n+        os.write(self.w_fd, data)\n+\n+    def wait_in_child(self, exit_code: int = 0) -\u003e int:\n+        self.close_write()\n+        self.read_bytes()\n+        self.close_read()\n+        return exit_code\n+\n+\n+@dataclass(frozen=True)\n+class NsTypeCase:\n+    name: str\n+    nstype: int\n+\n+\n+@dataclass(frozen=True)\n+class BadCloneCase:\n+    name: str\n+    flags: int\n+    exit_signal: int = int(signal.SIGCHLD)\n+    expected_errno: int = errno.EINVAL\n+\n+\n+@dataclass(frozen=True)\n+class SignalCase:\n+    name: str\n+    sig: int\n+    expected_errno: int\n+\n+\n+NS_TYPE_CASES: Final[tuple[NsTypeCase, ...]] = (\n+    NsTypeCase(\"mnt\", rc.CLONE_NEWNS),\n+    NsTypeCase(\"cgroup\", rc.CLONE_NEWCGROUP),\n+    NsTypeCase(\"uts\", rc.CLONE_NEWUTS),\n+    NsTypeCase(\"ipc\", rc.CLONE_NEWIPC),\n+    NsTypeCase(\"user\", rc.CLONE_NEWUSER),\n+    NsTypeCase(\"net\", rc.CLONE_NEWNET),\n+    NsTypeCase(\"time\", rc.CLONE_NEWTIME),\n+)\n+\n+BAD_CLONE_CASES: Final[tuple[BadCloneCase, ...]] = (\n+    BadCloneCase(\"newns\", rc.CLONE_NEWNS),\n+    BadCloneCase(\"newpid\", rc.CLONE_NEWPID),\n+    BadCloneCase(\"newuser\", rc.CLONE_NEWUSER),\n+    BadCloneCase(\"empty_mntns\", rc.CLONE_EMPTY_MNTNS),\n+    BadCloneCase(\"fs\", rc.CLONE_FS),\n+    BadCloneCase(\n+        \"thread\",\n+        rc.CLONE_THREAD | rc.CLONE_SIGHAND | rc.CLONE_VM,\n+        exit_signal=0,\n+    ),\n+    BadCloneCase(\"parent\", rc.CLONE_PARENT, exit_signal=0),\n+    BadCloneCase(\"sysvsem\", rc.CLONE_SYSVSEM),\n+    BadCloneCase(\"vm\", rc.CLONE_VM),\n+    BadCloneCase(\"vm_vfork\", rc.CLONE_VM | rc.CLONE_VFORK),\n+)\n+\n+BAD_SIGNAL_CASES: Final[tuple[SignalCase, ...]] = (\n+    SignalCase(\"negative\", -1, errno.EINVAL),\n+    SignalCase(\"out_of_range\", 9999, errno.EINVAL),\n+    SignalCase(\"empty_rootns\", 0, errno.ESRCH),\n+)\n+\n+\n+def _pause_forever() -\u003e int:\n+    signal.pause()\n+    return 0\n+\n+\n+def _reap_exit_code(pid: int) -\u003e int:\n+    _, status = os.waitpid(pid, 0)\n+    if os.WIFEXITED(status):\n+        return os.WEXITSTATUS(status)\n+    if os.WIFSIGNALED(status):\n+        return 128 + os.WTERMSIG(status)\n+    return 255\n+\n+\n+def _drop_to_uid(uid: int) -\u003e None:\n+    try:\n+        rc.setgroups_empty()\n+    except OSError as exc:\n+        if exc.errno != errno.EPERM:\n+            raise\n+    os.setresgid(uid, uid, uid)\n+    os.setresuid(uid, uid, uid)\n+    rc.prctl(rc.PR_SET_DUMPABLE, 1)\n+\n+\n+def _write_ugid_map(pid: int, host_uid: int, host_gid: int) -\u003e None:\n+    try:\n+        with open(f\"/proc/{pid}/setgroups\", \"wb\") as f:\n+            f.write(b\"deny\\n\")\n+    except OSError:\n+        pass\n+    with open(f\"/proc/{pid}/uid_map\", \"wb\") as f:\n+        f.write(f\"0 {host_uid} 1\\n\".encode())\n+    with open(f\"/proc/{pid}/gid_map\", \"wb\") as f:\n+        f.write(f\"0 {host_gid} 1\\n\".encode())\n+\n+\n+def _probe_pre_idmap_mkdir() -\u003e ProbeResult:\n+    try:\n+        cfd = rc.rootns()\n+    except OSError as exc:\n+        if exc.errno in SKIP_ERRNOS:\n+            return ProbeResult(False, f\"rootns() unavailable: {exc}\")\n+        raise\n+    try:\n+        try:\n+            mfd = rc.make_rootns_mount(cfd, \"tmpfs\")\n+        except OSError as exc:\n+            return ProbeResult(False, f\"tmpfs mount unavailable: {exc}\")\n+        try:\n+            os.mkdir(\"probe\", 0o755, dir_fd=mfd)\n+            return ProbeResult(True)\n+        except OSError as exc:\n+            if exc.errno == errno.EOVERFLOW:\n+                return ProbeResult(\n+                    False, \"pre-idmap submount setup requires mapped userns\"\n+                )\n+            raise\n+        finally:\n+            os.close(mfd)\n+    finally:\n+        os.close(cfd)\n+\n+\n+def _send_fd(sock: socket.socket, fd: int) -\u003e None:\n+    sock.sendmsg(\n+        [b\"F\"], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, ctypes.c_int(fd))]\n+    )\n+\n+\n+def _recv_fd(sock: socket.socket) -\u003e int:\n+    _, ancdata, _, _ = sock.recvmsg(\n+        1, socket.CMSG_SPACE(ctypes.sizeof(ctypes.c_int))\n+    )\n+    for cmsg_lvl, cmsg_type, cmsg_data in ancdata:\n+        if cmsg_lvl == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:\n+            buf = cmsg_data[: ctypes.sizeof(ctypes.c_int)]\n+            return int(ctypes.c_int.from_buffer_copy(buf).value)\n+    raise RuntimeError(\"missing SCM_RIGHTS fd\")\n+\n+\n+def _create_rootns_as_uid(uid: int) -\u003e tuple[int, int]:\n+    s_parent, s_child = socket.socketpair(socket.AF_UNIX, socket.SOCK_DGRAM)\n+    pid = os.fork()\n+    if pid == 0:\n+        s_parent.close()\n+        try:\n+            _drop_to_uid(uid)\n+            cfd = rc.rootns()\n+            _send_fd(s_child, cfd)\n+            os.close(cfd)\n+            os._exit(0)\n+        except OSError as exc:\n+            if exc.errno in SKIP_ERRNOS:\n+                os._exit(SKIP_EXIT)\n+            os._exit(1)\n+        finally:\n+            s_child.close()\n+    s_child.close()\n+    try:\n+        rlist, _, _ = select.select([s_parent], [], [], 5.0)\n+        cfd = _recv_fd(s_parent) if rlist else -1\n+    finally:\n+        s_parent.close()\n+    code = _reap_exit_code(pid)\n+    return code, cfd\n+\n+\n+class CellServiceTest(unittest.TestCase):\n+    tmpdir: str\n+    sock_path: str\n+    daemon_pid: int\n+    client: rc.CellClient\n+\n+    def setUp(self) -\u003e None:\n+        probe = _probe_pre_idmap_mkdir()\n+        if not probe.supported:\n+            self.skipTest(probe.reason)\n+        self.tmpdir = tempfile.mkdtemp(prefix=\"rootns-cells-\")\n+        self.sock_path = os.path.join(self.tmpdir, \"cells.sock\")\n+        self.daemon_pid = os.fork()\n+        if self.daemon_pid == 0:\n+            try:\n+                rc.CellService(self.sock_path).serve_forever()\n+                os._exit(0)\n+            except BaseException:\n+                os._exit(1)\n+        self.client = rc.CellClient(self.sock_path)\n+        for _ in range(50):\n+            if os.path.exists(self.sock_path):\n+                try:\n+                    if self.client.ping() == \"pong\":\n+                        break\n+                except OSError:\n+                    pass\n+            time.sleep(0.05)\n+        else:\n+            self.fail(\"CellService daemon failed to start\")\n+\n+    def tearDown(self) -\u003e None:\n+        daemon_pid = getattr(self, \"daemon_pid\", 0)\n+        if daemon_pid \u003e 0:\n+            try:\n+                self.client.shutdown()\n+            except Exception:\n+                os.kill(daemon_pid, signal.SIGKILL)\n+            _reap_exit_code(daemon_pid)\n+        tmpdir = getattr(self, \"tmpdir\", \"\")\n+        if tmpdir:\n+            shutil.rmtree(tmpdir, ignore_errors=True)\n+\n+    def test_cell_lifecycle_exec_and_hot_mount(self) -\u003e None:\n+        info = self.client.create(\"alpha\", mode=\"host\")\n+        self.assertEqual(info.state, \"created\")\n+        self.assertEqual(\n+            self.client.list_cells(),\n+            [rc.CellInfo(name=\"alpha\", state=\"created\")],\n+        )\n+\n+        started = self.client.start(\"alpha\", WAIT_MOUNT_PAYLOAD.argv())\n+        self.assertEqual(started.state, \"running\")\n+\n+        self.client.mount(\"alpha\", \"tmpfs\", \"/mnt\")\n+        self.client.exec_cmd(\"alpha\", WRITE_MOUNT_PAYLOAD.argv())\n+\n+        res = self.client.wait(\"alpha\")\n+        self.assertGreater(res.pid, 0)\n+        self.assertEqual(res.exit_code, 0)\n+\n+        self.client.destroy(\"alpha\")\n+        self.assertEqual(self.client.list_cells(), [])\n+\n+    def test_cell_broadcast_kill(self) -\u003e None:\n+        self.client.create(\"killme\", mode=\"host\")\n+        self.client.start(\"killme\", PAUSE_PAYLOAD.argv())\n+        self.client.exec_cmd(\"killme\", PAUSE_PAYLOAD.argv())\n+\n+        self.client.kill(\"killme\", int(signal.SIGKILL))\n+        res = self.client.wait(\"killme\")\n+        self.assertEqual(res.exit_code, -int(signal.SIGKILL))\n+        self.client.destroy(\"killme\")\n+\n+\n+class RootnsUapiTest(unittest.TestCase):\n+    probe: ProbeResult\n+    cell: rc.Cell | None\n+\n+    def setUp(self) -\u003e None:\n+        self.probe = _probe_pre_idmap_mkdir()\n+        self.cell = None\n+        if self.probe.supported:\n+            self.cell = rc.Cell(\"test\")\n+            self.cell.setup_rootfs(\n+                dirs=(\"proc\", \"tmp\", \"mnt\"), mount_procfs=True\n+            )\n+\n+    def tearDown(self) -\u003e None:\n+        if self.cell is not None:\n+            self.cell.close()\n+\n+    def _require_cell(self) -\u003e rc.Cell:\n+        if not self.probe.supported or self.cell is None:\n+            self.skipTest(self.probe.reason)\n+        return self.cell\n+\n+    def test_create_flags(self) -\u003e None:\n+        self._require_cell()\n+        with self.assertRaises(OSError) as cm:\n+            rc.rootns((~rc.ROOTNS_ALL_FLAGS) \u0026 0xFFFFFFFF)\n+        self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+    def test_get_nsfd(self) -\u003e None:\n+        try:\n+            cfd = rc.rootns()\n+        except OSError as exc:\n+            if exc.errno in SKIP_ERRNOS:\n+                self.skipTest(f\"rootns() unavailable: {exc}\")\n+            raise\n+        try:\n+            for case in NS_TYPE_CASES:\n+                with self.subTest(ns=case.name):\n+                    nsfd = rc.rootns_get_nsfd(cfd, case.nstype)\n+                    try:\n+                        self.assertEqual(\n+                            rc.raw_ioctl(nsfd, rc.NS_GET_NSTYPE), case.nstype\n+                        )\n+                    finally:\n+                        os.close(nsfd)\n+\n+            with self.assertRaises(OSError) as cm:\n+                rc.rootns_get_nsfd(cfd, rc.CLONE_NEWPID)\n+            self.assertEqual(cm.exception.errno, errno.ESRCH)\n+\n+            with self.assertRaises(OSError) as cm:\n+                rc.rootns_get_nsfd(cfd, 0)\n+            self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+            mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)\n+            rootfd = rc.make_rootns_mount(cfd, \"tmpfs\")\n+            rc.move_mount(\n+                rootfd,\n+                \"\",\n+                mntns_fd,\n+                \"/\",\n+                rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+            )\n+            os.close(rootfd)\n+            os.close(mntns_fd)\n+\n+            hold = SyncPipe.create()\n+            pid = rc.run_in_rootns(cfd, hold.wait_in_child)\n+            hold.close_read()\n+            try:\n+                nsfd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWPID)\n+                try:\n+                    self.assertEqual(\n+                        rc.raw_ioctl(nsfd, rc.NS_GET_NSTYPE), rc.CLONE_NEWPID\n+                    )\n+                finally:\n+                    os.close(nsfd)\n+            finally:\n+                hold.close_write()\n+                self.assertEqual(_reap_exit_code(pid), 0)\n+        finally:\n+            os.close(cfd)\n+\n+    def test_wait_poll_and_clone_dead(self) -\u003e None:\n+        cell = self._require_cell()\n+        cfd = cell.cfd\n+\n+        with self.assertRaises(OSError) as cm:\n+            rc.raw_ioctl(cfd, rc.ROOTNS_WAIT, 0)\n+        self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+        with self.assertRaises(OSError) as cm:\n+            rc.rootns_wait(cfd, (~os.WNOHANG) \u0026 0xFFFFFFFF)\n+        self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+        for wait_flags in (0, os.WNOHANG):\n+            with self.assertRaises(OSError) as cm:\n+                rc.rootns_wait(cfd, wait_flags)\n+            self.assertEqual(cm.exception.errno, errno.ECHILD)\n+\n+        hold = SyncPipe.create()\n+        pid = rc.run_in_rootns(cfd, lambda: hold.wait_in_child(42))\n+        hold.close_read()\n+\n+        self.assertEqual(\n+            rc.rootns_wait(cfd, os.WNOHANG), rc.WaitResult(0, 0)\n+        )\n+        poller = select.poll()\n+        poller.register(cfd, select.POLLIN)\n+        self.assertEqual(poller.poll(0), [])\n+\n+        hold.close_write()\n+        events = poller.poll(5000)\n+        self.assertTrue(any(ev \u0026 select.POLLHUP for _, ev in events))\n+\n+        res = rc.rootns_wait(cfd, os.WNOHANG)\n+        self.assertEqual(res.pid, pid)\n+        self.assertEqual(res.exit_code, 42)\n+        self.assertEqual(_reap_exit_code(pid), 42)\n+\n+        with self.assertRaises(OSError) as cm:\n+            rc.clone_into_rootns(cfd)\n+        self.assertEqual(cm.exception.errno, errno.ESRCH)\n+\n+    def test_kill_ioctl_and_kill_on_close(self) -\u003e None:\n+        cell = self._require_cell()\n+        cfd = cell.cfd\n+\n+        for case in BAD_SIGNAL_CASES:\n+            with self.subTest(sig=case.name):\n+                with self.assertRaises(OSError) as cm:\n+                    rc.rootns_kill(cfd, case.sig)\n+                self.assertEqual(cm.exception.errno, case.expected_errno)\n+\n+        ready = SyncPipe.create()\n+        hold = SyncPipe.create()\n+\n+        def init_proc() -\u003e int:\n+            ready.close()\n+            hold.close()\n+            signal.pause()\n+            return 0\n+\n+        def member_proc() -\u003e int:\n+            ready.close_read()\n+            hold.close_read()\n+            os.setsid()\n+            gc = os.fork()\n+            if gc == 0:\n+                ready.write_bytes(b\"r\")\n+                ready.close_write()\n+                signal.pause()\n+                os._exit(0)\n+            ready.close_write()\n+            signal.pause()\n+            return 0\n+\n+        pid1 = rc.run_in_rootns(cfd, init_proc)\n+        pid2 = rc.run_in_rootns(cfd, member_proc)\n+        ready.close_write()\n+        hold.close_write()\n+\n+        self.assertEqual(ready.read_bytes(), b\"r\")\n+        ready.close_read()\n+\n+        rc.rootns_kill(cfd, 0)\n+        rc.rootns_kill(cfd, int(signal.SIGKILL))\n+        self.assertEqual(hold.read_bytes(), b\"\")\n+        hold.close_read()\n+\n+        self.assertEqual(_reap_exit_code(pid2), 128 + int(signal.SIGKILL))\n+        self.assertEqual(_reap_exit_code(pid1), 128 + int(signal.SIGKILL))\n+\n+        with rc.Cell(\n+            \"koc\", flags=rc.ROOTNS_KILL_ON_CLOSE | rc.ROOTNS_CLOSE_ON_EXEC\n+        ) as cell2:\n+            cell2.setup_rootfs(mount_procfs=False)\n+            pid_koc = rc.run_in_rootns(cell2.cfd, _pause_forever)\n+        self.assertEqual(_reap_exit_code(pid_koc), 128 + int(signal.SIGKILL))\n+\n+    def test_proc_submount_and_nested_namespaces(self) -\u003e None:\n+        cell = self._require_cell()\n+        cell.mount_fs(\"tmpfs\", \"mnt\")\n+\n+        def inside() -\u003e int:\n+            if os.getpid() != 1:\n+                return 1\n+            pids = [e for e in os.listdir(\"/proc\") if e.isdigit()]\n+            if pids != [\"1\"]:\n+                return 2\n+            with open(\"/mnt/hello\", \"wb\") as f:\n+                f.write(b\"ok\")\n+            rc.unshare(rc.CLONE_NEWUTS | rc.CLONE_NEWIPC | rc.CLONE_NEWNET)\n+            return 0\n+\n+        pid = rc.run_in_rootns(cell.cfd, inside)\n+        res = cell.wait()\n+        self.assertEqual(res.pid, pid)\n+        self.assertEqual(res.exit_code, 0)\n+        self.assertEqual(_reap_exit_code(pid), 0)\n+\n+    def test_setns_owner_vs_foreign(self) -\u003e None:\n+        cell = self._require_cell()\n+        hold = SyncPipe.create()\n+        pid = rc.run_in_rootns(cell.cfd, hold.wait_in_child)\n+        hold.close_read()\n+        try:\n+            uts_fd = os.open(\n+                f\"/proc/{pid}/ns/uts\", os.O_RDONLY | os.O_CLOEXEC\n+            )\n+            try:\n+                w1 = os.fork()\n+                if w1 == 0:\n+                    try:\n+                        rc.setns(uts_fd, rc.CLONE_NEWUTS)\n+                        os._exit(0)\n+                    except BaseException:\n+                        os._exit(1)\n+                self.assertEqual(_reap_exit_code(w1), 0)\n+\n+                if os.geteuid() == 0:\n+                    w2 = os.fork()\n+                    if w2 == 0:\n+                        try:\n+                            _drop_to_uid(1000)\n+                        except OSError:\n+                            os._exit(0)\n+                        try:\n+                            rc.setns(uts_fd, rc.CLONE_NEWUTS)\n+                            os._exit(2)\n+                        except OSError as exc:\n+                            os._exit(0 if exc.errno == errno.EPERM else 3)\n+                    self.assertEqual(_reap_exit_code(w2), 0)\n+            finally:\n+                os.close(uts_fd)\n+        finally:\n+            hold.close_write()\n+            _reap_exit_code(pid)\n+\n+    def test_mount_and_fsconfig_validation(self) -\u003e None:\n+        self._require_cell()\n+        cfd = rc.rootns()\n+        mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)\n+        try:\n+            with self.assertRaises(OSError) as cm:\n+                rc.move_mount(\n+                    rc.AT_FDCWD, \"/\", mntns_fd, \"/\", rc.MOVE_MOUNT_T_MNTNS\n+                )\n+            self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+            m1 = rc.make_rootns_mount(cfd, \"tmpfs\")\n+            try:\n+                rc.move_mount(\n+                    m1,\n+                    \"\",\n+                    mntns_fd,\n+                    \"/\",\n+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                )\n+            finally:\n+                os.close(m1)\n+\n+            m2 = rc.make_rootns_mount(cfd, \"tmpfs\")\n+            try:\n+                for alias in (\"/\", \".\"):\n+                    with self.assertRaises(OSError) as cm:\n+                        rc.move_mount(\n+                            m2,\n+                            \"\",\n+                            mntns_fd,\n+                            alias,\n+                            rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                        )\n+                    self.assertEqual(cm.exception.errno, errno.EBUSY)\n+                with self.assertRaises(OSError) as cm:\n+                    rc.move_mount(\n+                        m2,\n+                        \"\",\n+                        mntns_fd,\n+                        \".\",\n+                        rc.MOVE_MOUNT_F_EMPTY_PATH\n+                        | rc.MOVE_MOUNT_T_MNTNS\n+                        | rc.MOVE_MOUNT_BENEATH,\n+                    )\n+                self.assertEqual(cm.exception.errno, errno.EINVAL)\n+            finally:\n+                os.close(m2)\n+\n+            fsfd = rc.fsopen(\"tmpfs\")\n+            try:\n+                rc.fsconfig(fsfd, rc.FSCONFIG_SET_ROOTNS, aux=cfd)\n+                with self.assertRaises(OSError) as cm:\n+                    rc.fsconfig(fsfd, rc.FSCONFIG_SET_ROOTNS, aux=cfd)\n+                self.assertEqual(cm.exception.errno, errno.EBUSY)\n+            finally:\n+                os.close(fsfd)\n+\n+            bad_proc = rc.fsopen(\"proc\")\n+            try:\n+                w_nonanc = os.fork()\n+                if w_nonanc == 0:\n+                    try:\n+                        rc.unshare(rc.CLONE_NEWPID)\n+                        inner = os.fork()\n+                        if inner == 0:\n+                            try:\n+                                rc.fsconfig(\n+                                    bad_proc, rc.FSCONFIG_SET_ROOTNS, aux=cfd\n+                                )\n+                                os._exit(1)\n+                            except OSError as exc:\n+                                if exc.errno != errno.EINVAL:\n+                                    os._exit(2)\n+                            try:\n+                                rc.fsconfig(bad_proc, rc.FSCONFIG_CMD_CREATE)\n+                                os._exit(3)\n+                            except OSError as exc:\n+                                os._exit(0 if exc.errno == errno.EBUSY else 4)\n+                        os._exit(_reap_exit_code(inner))\n+                    except BaseException:\n+                        os._exit(5)\n+                self.assertEqual(_reap_exit_code(w_nonanc), 0)\n+            finally:\n+                os.close(bad_proc)\n+\n+            cfd_lock = rc.rootns()\n+            lock_mntns = rc.rootns_get_nsfd(cfd_lock, rc.CLONE_NEWNS)\n+            try:\n+                rfd = rc.make_rootns_mount(cfd_lock, \"tmpfs\")\n+                os.mkdir(\"host_sub\", 0o755, dir_fd=rfd)\n+                sfd = rc.open_tree(\n+                    rc.AT_FDCWD,\n+                    \"/tmp\",\n+                    rc.OPEN_TREE_CLONE\n+                    | rc.AT_RECURSIVE\n+                    | rc.OPEN_TREE_CLOEXEC,\n+                )\n+                rc.move_mount(\n+                    sfd, \"\", rfd, \"host_sub\", rc.MOVE_MOUNT_F_EMPTY_PATH\n+                )\n+                os.close(sfd)\n+                rc.move_mount(\n+                    rfd,\n+                    \"\",\n+                    lock_mntns,\n+                    \"/\",\n+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                )\n+                os.close(rfd)\n+\n+                def try_umount_locked() -\u003e int:\n+                    try:\n+                        rc.umount2(\"/host_sub\", rc.MNT_DETACH)\n+                        return 1\n+                    except OSError as exc:\n+                        return 0 if exc.errno == errno.EINVAL else 2\n+\n+                p_lock = rc.run_in_rootns(cfd_lock, try_umount_locked)\n+                self.assertEqual(_reap_exit_code(p_lock), 0)\n+            finally:\n+                os.close(lock_mntns)\n+                os.close(cfd_lock)\n+\n+            if os.geteuid() == 0:\n+                code, u_cfd = _create_rootns_as_uid(1000)\n+                if code == 0 and u_cfd \u003e= 0:\n+                    try:\n+                        u_mntns = rc.rootns_get_nsfd(u_cfd, rc.CLONE_NEWNS)\n+                        m_root = rc.make_rootns_mount(u_cfd, \"tmpfs\")\n+                        rc.move_mount(\n+                            m_root,\n+                            \"\",\n+                            u_mntns,\n+                            \"/\",\n+                            rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                        )\n+                        os.close(m_root)\n+\n+                        attacker = os.fork()\n+                        if attacker == 0:\n+                            try:\n+                                _drop_to_uid(2000)\n+                            except OSError:\n+                                os._exit(0)\n+                            fsfd2 = rc.fsopen(\"tmpfs\")\n+                            try:\n+                                rc.fsconfig(\n+                                    fsfd2, rc.FSCONFIG_SET_ROOTNS, aux=u_cfd\n+                                )\n+                                os._exit(1)\n+                            except OSError as exc:\n+                                if exc.errno != errno.EPERM:\n+                                    os._exit(2)\n+                            finally:\n+                                os.close(fsfd2)\n+                            try:\n+                                rc.clone_into_rootns(u_cfd)\n+                                os._exit(3)\n+                            except OSError as exc:\n+                                if exc.errno != errno.EPERM:\n+                                    os._exit(4)\n+                            os._exit(0)\n+                        self.assertEqual(_reap_exit_code(attacker), 0)\n+                        os.close(u_mntns)\n+                    finally:\n+                        os.close(u_cfd)\n+        finally:\n+            os.close(mntns_fd)\n+            os.close(cfd)\n+\n+    def test_clone_flags_and_pidns_ancestry(self) -\u003e None:\n+        cell = self._require_cell()\n+        cfd = cell.cfd\n+\n+        empty_cfd = rc.rootns()\n+        try:\n+            with self.assertRaises(OSError) as cm:\n+                rc.clone_into_rootns(empty_cfd, rc.CLONE_VFORK)\n+            self.assertEqual(cm.exception.errno, errno.ENOENT)\n+        finally:\n+            os.close(empty_cfd)\n+\n+        args = rc.CloneArgs(\n+            flags=rc.CLONE_INTO_ROOTNS,\n+            exit_signal=int(signal.SIGCHLD),\n+            rootns=cfd,\n+        )\n+        with self.assertRaises(OSError) as cm:\n+            rc.clone3_raw(args, size=rc.CLONE_ARGS_SIZE_VER2)\n+        self.assertEqual(cm.exception.errno, errno.EINVAL)\n+\n+        for case in BAD_CLONE_CASES:\n+            with self.subTest(flag=case.name):\n+                with self.assertRaises(OSError) as cm:\n+                    rc.clone_into_rootns(\n+                        cfd,\n+                        extra_flags=case.flags,\n+                        exit_signal=case.exit_signal,\n+                    )\n+                self.assertEqual(cm.exception.errno, case.expected_errno)\n+\n+        allowed = (\n+            rc.CLONE_VFORK\n+            | rc.CLONE_PIDFD\n+            | rc.CLONE_CLEAR_SIGHAND\n+            | rc.CLONE_NNP\n+        )\n+        old_umask = os.umask(0o077)\n+        try:\n+            rc.prctl(rc.PR_SET_DUMPABLE, 1)\n+            pid, pidfd = rc.clone_into_rootns(cfd, extra_flags=allowed)\n+            if pid == 0:\n+                cur_umask = os.umask(0o022)\n+                dumpable = rc.prctl(rc.PR_GET_DUMPABLE)\n+                ok = (\n+                    os.getpid() == 1\n+                    and rc.prctl(rc.PR_GET_NO_NEW_PRIVS) == 1\n+                    and cur_umask == 0o077\n+                    and dumpable != 1\n+                )\n+                os._exit(0 if ok else 1)\n+        finally:\n+            os.umask(old_umask)\n+        self.assertGreaterEqual(pidfd, 0)\n+        os.close(pidfd)\n+        self.assertEqual(_reap_exit_code(pid), 0)\n+\n+        with rc.Cell(\"exdev\") as cell2:\n+            cell2.setup_rootfs(mount_procfs=False)\n+            w = os.fork()\n+            if w == 0:\n+                try:\n+                    rc.unshare(rc.CLONE_NEWPID)\n+                    inner = os.fork()\n+                    if inner == 0:\n+                        try:\n+                            rc.clone_into_rootns(cell2.cfd)\n+                            os._exit(1)\n+                        except OSError as exc:\n+                            os._exit(0 if exc.errno == errno.EXDEV else 2)\n+                    os._exit(_reap_exit_code(inner))\n+                except BaseException:\n+                    os._exit(3)\n+            self.assertEqual(_reap_exit_code(w), 0)\n+\n+    def test_concurrent_bootstrap(self) -\u003e None:\n+        cell = self._require_cell()\n+        cfd = cell.cfd\n+        start = SyncPipe.create()\n+        ready = SyncPipe.create()\n+        init_gate = SyncPipe.create()\n+        peer_gate = SyncPipe.create()\n+\n+        workers: list[int] = []\n+        for idx in range(4):\n+            wpid = os.fork()\n+            if wpid == 0:\n+                start.close_write()\n+                ready.close_read()\n+                init_gate.close_write()\n+                peer_gate.close_write()\n+                start.read_bytes()\n+                start.close_read()\n+\n+                def entrant(worker_idx: int = idx) -\u003e int:\n+                    my_pid = os.getpid()\n+                    ready.write_bytes(bytes([worker_idx, my_pid]))\n+                    ready.close_write()\n+                    gate = init_gate if my_pid == 1 else peer_gate\n+                    gate.read_bytes()\n+                    init_gate.close_read()\n+                    peer_gate.close_read()\n+                    return 0\n+\n+                cpid = rc.run_in_rootns(cfd, entrant)\n+                ready.close_write()\n+                init_gate.close_read()\n+                peer_gate.close_read()\n+                os._exit(0 if _reap_exit_code(cpid) == 0 else 1)\n+            workers.append(wpid)\n+\n+        start.close_read()\n+        ready.close_write()\n+        init_gate.close_read()\n+        peer_gate.close_read()\n+        start.close_write()\n+\n+        seen_pids: set[int] = set()\n+        init_idx = -1\n+        for _ in range(4):\n+            msg = ready.read_bytes(2)\n+            self.assertEqual(len(msg), 2)\n+            if msg[1] == 1:\n+                init_idx = msg[0]\n+            seen_pids.add(msg[1])\n+        ready.close_read()\n+\n+        self.assertEqual(seen_pids, {1, 2, 3, 4})\n+        self.assertGreaterEqual(init_idx, 0)\n+\n+        peer_gate.close_write()\n+        for i, wpid in enumerate(workers):\n+            if i != init_idx:\n+                self.assertEqual(_reap_exit_code(wpid), 0)\n+        init_gate.close_write()\n+        self.assertEqual(_reap_exit_code(workers[init_idx]), 0)\n+\n+        res = cell.wait()\n+        self.assertGreater(res.pid, 0)\n+        self.assertEqual(res.exit_code, 0)\n+\n+    def test_pivot_root_and_standalone_mntns_hot_mount(self) -\u003e None:\n+        cell = self._require_cell()\n+        go = SyncPipe.create()\n+        ready = SyncPipe.create()\n+        hold = SyncPipe.create()\n+\n+        def init_pivot() -\u003e int:\n+            go.close_write()\n+            ready.close_read()\n+            hold.close_write()\n+            if go.read_bytes() != b\"g\":\n+                return 1\n+            go.close_read()\n+            tfd = rc.fsopen(\"tmpfs\")\n+            rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)\n+            mfd = rc.fsmount(tfd)\n+            os.close(tfd)\n+            os.mkdir(\"old_root\", 0o755, dir_fd=mfd)\n+            os.mkdir(\"sub\", 0o755, dir_fd=mfd)\n+            pfd = os.open(\n+                \"pivoted\",\n+                os.O_CREAT | os.O_WRONLY | os.O_CLOEXEC,\n+                0o644,\n+                dir_fd=mfd,\n+            )\n+            os.close(pfd)\n+            rc.move_mount(\n+                mfd, \"\", rc.AT_FDCWD, \"/mnt\", rc.MOVE_MOUNT_F_EMPTY_PATH\n+            )\n+            os.close(mfd)\n+            os.chdir(\"/mnt\")\n+            rc.pivot_root(\".\", \"old_root\")\n+            os.chdir(\"/\")\n+            rc.umount2(\"/old_root\", rc.MNT_DETACH)\n+            ready.write_bytes(b\"p\")\n+            ready.close_write()\n+            hold.read_bytes()\n+            hold.close_read()\n+            return 0\n+\n+        pid1 = rc.run_in_rootns(cell.cfd, init_pivot)\n+        go.close_read()\n+        ready.close_write()\n+        hold.close_read()\n+        try:\n+            _write_ugid_map(pid1, os.geteuid(), os.getegid())\n+            go.write_bytes(b\"g\")\n+            go.close_write()\n+\n+            self.assertEqual(ready.read_bytes(), b\"p\")\n+            ready.close_read()\n+\n+            cell.mount_fs(\"tmpfs\", \"sub\")\n+\n+            pid2 = rc.run_in_rootns(\n+                cell.cfd,\n+                lambda: (\n+                    0\n+                    if os.path.exists(\"/pivoted\") and os.path.ismount(\"/sub\")\n+                    else 1\n+                ),\n+            )\n+            self.assertEqual(_reap_exit_code(pid2), 0)\n+        finally:\n+            hold.close_write()\n+            self.assertEqual(_reap_exit_code(pid1), 0)\n+\n+        ext_ready = SyncPipe.create()\n+        ext_hold = SyncPipe.create()\n+        plain_pid = os.fork()\n+        if plain_pid == 0:\n+            ext_ready.close_read()\n+            ext_hold.close_write()\n+            try:\n+                rc.unshare(rc.CLONE_NEWNS)\n+                rc.make_mount_private(\"/\")\n+                tfd = rc.fsopen(\"tmpfs\")\n+                rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)\n+                mfd = rc.fsmount(tfd)\n+                os.close(tfd)\n+                rc.move_mount(\n+                    mfd, \"\", rc.AT_FDCWD, \"/tmp\", rc.MOVE_MOUNT_F_EMPTY_PATH\n+                )\n+                os.close(mfd)\n+                os.mkdir(\"/tmp/target\", 0o755)\n+                ext_ready.write_bytes(b\"r\")\n+                ext_ready.close_write()\n+                ext_hold.read_bytes()\n+                ext_hold.close_read()\n+                os._exit(0 if os.path.ismount(\"/tmp/target\") else 2)\n+            except BaseException:\n+                os._exit(1)\n+        ext_ready.close_write()\n+        ext_hold.close_read()\n+        try:\n+            self.assertEqual(ext_ready.read_bytes(), b\"r\")\n+            ext_ready.close_read()\n+            ext_mntns = os.open(\n+                f\"/proc/{plain_pid}/ns/mnt\", os.O_RDONLY | os.O_CLOEXEC\n+            )\n+            try:\n+                tfd = rc.fsopen(\"tmpfs\")\n+                rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)\n+                mfd = rc.fsmount(tfd)\n+                os.close(tfd)\n+                with self.assertRaises(OSError) as cm:\n+                    rc.move_mount(\n+                        mfd,\n+                        \"\",\n+                        ext_mntns,\n+                        \"tmp/..\",\n+                        rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                    )\n+                self.assertEqual(cm.exception.errno, errno.EBUSY)\n+                with self.assertRaises(OSError) as cm:\n+                    rc.move_mount(\n+                        mfd,\n+                        \"\",\n+                        ext_mntns,\n+                        \"tmp/..\",\n+                        rc.MOVE_MOUNT_F_EMPTY_PATH\n+                        | rc.MOVE_MOUNT_T_MNTNS\n+                        | rc.MOVE_MOUNT_BENEATH,\n+                    )\n+                self.assertEqual(cm.exception.errno, errno.EINVAL)\n+                rc.move_mount(\n+                    mfd,\n+                    \"\",\n+                    ext_mntns,\n+                    \"tmp/target\",\n+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                )\n+                os.close(mfd)\n+            finally:\n+                os.close(ext_mntns)\n+        finally:\n+            ext_hold.close_write()\n+        self.assertEqual(_reap_exit_code(plain_pid), 0)\n+\n+    def test_unprivileged_without_entering_userns(self) -\u003e None:\n+        worker = os.fork()\n+        if worker == 0:\n+            try:\n+                if os.geteuid() == 0:\n+                    try:\n+                        _drop_to_uid(1000)\n+                    except OSError as exc:\n+                        if exc.errno == errno.EINVAL:\n+                            os._exit(SKIP_EXIT)\n+                        os._exit(1)\n+\n+                try:\n+                    tfd = rc.fsopen(\"tmpfs\")\n+                except OSError as exc:\n+                    if exc.errno != errno.EPERM:\n+                        os._exit(2)\n+                else:\n+                    try:\n+                        rc.fsconfig(tfd, rc.FSCONFIG_CMD_CREATE)\n+                        os._exit(3)\n+                    except OSError as exc:\n+                        if exc.errno != errno.EPERM:\n+                            os._exit(4)\n+                    finally:\n+                        os.close(tfd)\n+\n+                try:\n+                    cfd = rc.rootns()\n+                except OSError as exc:\n+                    if exc.errno in SKIP_ERRNOS:\n+                        os._exit(SKIP_EXIT)\n+                    os._exit(5)\n+\n+                mntns_fd = rc.rootns_get_nsfd(cfd, rc.CLONE_NEWNS)\n+                rootfd = rc.make_rootns_mount(cfd, \"tmpfs\")\n+                rc.move_mount(\n+                    rootfd,\n+                    \"\",\n+                    mntns_fd,\n+                    \"/\",\n+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                )\n+                os.close(rootfd)\n+\n+                go = SyncPipe.create()\n+                ack = SyncPipe.create()\n+\n+                def unpriv_init() -\u003e int:\n+                    go.close_write()\n+                    ack.close_read()\n+                    rc.prctl(rc.PR_SET_DUMPABLE, 1)\n+                    ack.write_bytes(b\"d\")\n+                    if go.read_bytes() != b\"1\":\n+                        return 1\n+                    os.mkdir(\"/proc\", 0o755)\n+                    ack.write_bytes(b\"m\")\n+                    ack.close_write()\n+                    if go.read_bytes() != b\"2\":\n+                        return 2\n+                    go.close_read()\n+                    pids = [e for e in os.listdir(\"/proc\") if e.isdigit()]\n+                    return 0 if pids == [\"1\"] else 3\n+\n+                pid = rc.run_in_rootns(cfd, unpriv_init)\n+                go.close_read()\n+                ack.close_write()\n+\n+                if ack.read_bytes() != b\"d\":\n+                    os._exit(6)\n+                _write_ugid_map(pid, os.geteuid(), os.getegid())\n+                go.write_bytes(b\"1\")\n+                if ack.read_bytes() != b\"m\":\n+                    os._exit(6)\n+                ack.close_read()\n+\n+                pfd = rc.make_rootns_mount(cfd, \"proc\")\n+                rc.move_mount(\n+                    pfd,\n+                    \"\",\n+                    mntns_fd,\n+                    \"proc\",\n+                    rc.MOVE_MOUNT_F_EMPTY_PATH | rc.MOVE_MOUNT_T_MNTNS,\n+                )\n+                os.close(pfd)\n+                os.close(mntns_fd)\n+\n+                go.write_bytes(b\"2\")\n+                go.close_write()\n+\n+                res = rc.rootns_wait(cfd)\n+                os.close(cfd)\n+                if res.pid != pid or res.exit_code != 0:\n+                    os._exit(7)\n+                if _reap_exit_code(pid) != 0:\n+                    os._exit(8)\n+                os._exit(0)\n+            except BaseException:\n+                os._exit(9)\n+\n+        code = _reap_exit_code(worker)\n+        if code == SKIP_EXIT:\n+            self.skipTest(\"unprivileged rootns unavailable\")\n+        self.assertEqual(code, 0)\n+\n+\n+if __name__ == \"__main__\":\n+    unittest.main()\ndiff --git a/tools/testing/selftests/rootns/test_smoke.sh b/tools/testing/selftests/rootns/test_smoke.sh\nnew file mode 100755\nindex 00000000000000..2cb23ca2ad290a\n--- /dev/null\n+++ b/tools/testing/selftests/rootns/test_smoke.sh\n@@ -0,0 +1,11 @@\n+#!/bin/sh\n+# SPDX-License-Identifier: GPL-2.0\n+\n+# Kselftest framework requirement - SKIP code is 4.\n+ksft_skip=4\n+\n+command -v python3 \u003e/dev/null 2\u003e\u00261 || exit $ksft_skip\n+\n+DIR=\"$(dirname \"$(readlink -f \"$0\")\")\"\n+PYTHONPATH=\"$DIR${PYTHONPATH:+:$PYTHONPATH}\" \\\n+\tpython3 -m unittest -v rootns_test 2\u003e\u00261\n"
}

2/1 2026/11/24 16:16 agent patch-evaluator
30m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "ROOTNS",
    "NAMESPACES",
    "USER_NS",
    "PID_NS",
    "UTS_NS",
    "IPC_NS",
    "NET_NS",
    "CGROUPS",
    "TIME_NS",
    "POSIX_MQUEUE",
    "PROC_FS",
    "SECURITY"
  ],
  "FocusSymbols": [
    "sys_rootns",
    "__x64_sys_rootns",
    "rootns_ioctl",
    "rootns_prepare_fork",
    "rootns_finish_fork",
    "copy_rootns",
    "exit_rootns",
    "fsconfig_set_rootns",
    "move_mount_mntns",
    "mnt_ns_get_root",
    "nsproxy_open_namespace",
    "proc_set_rootns",
    "mqueue_set_rootns"
  ],
  "Reasoning": "The patch introduces the root namespace (CONFIG_ROOTNS) subsystem, providing a new rootns() syscall, new ioctls (ROOTNS_GET_NSFD, ROOTNS_WAIT, ROOTNS_KILL), a new clone3 flag (CLONE_INTO_ROOTNS), fsconfig commands (FSCONFIG_SET_ROOTNS), and move_mount operations (MOVE_MOUNT_T_MNTNS). These modify core namespace, fork, VFS, and security subsystem logic that is directly reachable from userspace in standard virtualized environments. Fuzzing is highly warranted to test complex lifecycle transitions, concurrency, and security invariants.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 5eee798c49d5a9e72c751aa7953598064d617c03
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Nov 24 16:16:22 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a85c..56d0ac4eb0879a 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 dbe46204099996..d8dc926ea28303 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 00000000000000..5326fd2eeb2123
--- /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
diff --git a/MAINTAINERS b/MAINTAINERS
index 8fd9991739547c..a24d0b16f42f42 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -24511,6 +24511,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
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df41..ea790cceb67acf 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 55717ed32c27e6..531b2a2dce72d1 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 df2d1d82fb3ccf..8ef224c0dd42b6 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 ba7a4d8903d044..77239262dc26f5 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 76d7cbe2a133c4..df53332ce4a5b7 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 9ae88e4eac61ee..84db40158bf0b3 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 83dc93a0712f12..9e874a95850300 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 9c62429c9b7b4e..592c2225f4ce36 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 88adc4016cce01..93f8539bd1795d 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 cfbb70039ff007..7e12f74a27c1b4 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 1b45e68a217bb0..ab303fbb86f380 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 ace068dff0de03..e92778075bcb48 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 5b9fe0e8140f26..20d6c572d3f153 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 2c172ef48dfd33..98cb11b717e5ca 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 d5b6045b0090cc..674fa2b4b23878 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 d354bb231796c2..82b7344a099cb3 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/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb70..db5a5c7a07db01 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 3083d904df9bc6..9429844bf6bf9d 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 a50584df97bea7..cd004750b99c5b 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 70024870fefa2e..85b31af68a4d65 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 3f2fbac40f8ee5..d6815bf6ea9bb7 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 aecd05ac01705d..36ed48c3f64678 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);
 }
 
 /*
@@ -4614,16 +4653,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 +4700,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 +4750,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;
@@ -4725,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;
 
@@ -4736,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);
 }
 
 /*
@@ -4758,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)
@@ -4771,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;
@@ -4794,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);
 }
 
 /*
@@ -6582,6 +6743,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 +6773,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 +6796,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 +6817,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",
@@ -6708,6 +6880,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/fs/nsfs.c b/fs/nsfs.c
index 8179d69da03871..1de51cd475080e 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/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a71..323296b030892d 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/cred.h b/include/linux/cred.h
index 49c26af3734908..9849366fd44b87 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/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5e2..42648bec5cfa36 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/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb26..2cb90ddedc14a2 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 13621e9e233e6b..217a59d428b158 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/mnt_namespace.h b/include/linux/mnt_namespace.h
index 0acd1089d149cf..98188d1f74280c 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/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fecd1..bfba790ee1a7fb 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/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f09240..26b3b788cc909f 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -12,6 +12,8 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct rootns;
+struct user_namespace;
 
 /*
  * A structure to contain pointers to all per-process
@@ -92,7 +94,12 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *
  */
 
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+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,
+		    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/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b75..6fd959f4d0d4da 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
new file mode 100644
index 00000000000000..795a79584231d9
--- /dev/null
+++ b/include/linux/rootns.h
@@ -0,0 +1,92 @@
+/* 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 kernel_clone_args;
+struct nsproxy;
+struct pid;
+struct pid_namespace;
+struct task_struct;
+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' */
+#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) */
+	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);
+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)
+{
+	return NULL;
+}
+
+static inline void put_rootns(struct rootns *c)
+{
+}
+
+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)
+{
+}
+
+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 90ed5bc3c7afee..e0c4e8ab02f154 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/security.h b/include/linux/security.h
index 40831fab54709a..995292f1c92eb9 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/include/linux/syscalls.h b/include/linux/syscalls.h
index 552d9710a0d574..7e630b612ef26c 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 58bd9728df5838..bdc185543893df 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/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d8d..3600a903442e2b 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/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736ee..25902ed39d79c3 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/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index ac865edac5173e..7fa93de08ceb6c 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.
@@ -105,6 +106,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/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
new file mode 100644
index 00000000000000..acd91d895c632d
--- /dev/null
+++ b/include/uapi/linux/rootns.h
@@ -0,0 +1,83 @@
+/* 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>
+#include <linux/types.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,
+};
+
+/**
+ * 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
+
+/**
+ * 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)
+
+/**
+ * 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)
+
+/**
+ * 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/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba894283e..405cfc954ae181 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/init/Kconfig b/init/Kconfig
index c8a7cfa60a6ea4..ed93dd11e6ac1f 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/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c4477..f94e9b566bd03b 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,
 };
 
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c52..7074d2664ce711 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/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922d0..bbcf1433fdc25a 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/cred.c b/kernel/cred.c
index d01df40a9a3861..48a8852dab4a06 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 5efceb8d58a78b..ac0497ff410cb9 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>
@@ -83,6 +84,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>
@@ -1615,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);
@@ -1631,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;
 
@@ -1648,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;
@@ -1670,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;
 }
 
@@ -2185,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;
 
@@ -2316,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);
@@ -2328,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);
@@ -2509,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;
@@ -2576,6 +2622,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, clone_args_rootns(args));
 		nr_threads++;
 	}
 	total_forks++;
@@ -2777,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
@@ -2798,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);
 
@@ -2955,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;
@@ -2985,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),
@@ -2996,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 &&
@@ -3036,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;
 
 	/*
@@ -3060,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 2dcf105e8ee2d4..78a1e1fb2cfd7f 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>
@@ -85,9 +86,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 +98,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;
 
@@ -166,12 +167,18 @@ static 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, 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);
 
@@ -231,7 +238,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 +296,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 +363,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);
 
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e7040..081c27aa85bd18 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
new file mode 100644
index 00000000000000..3733a249fecaa1
--- /dev/null
+++ b/kernel/rootns.c
@@ -0,0 +1,581 @@
+// 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/fs_struct.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 <linux/security.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;
+}
+
+static void free_rootns(struct rootns *c)
+{
+	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);
+}
+
+/*
+ * 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.
+ */
+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_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 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 ret;
+	int nr;
+
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+	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) {
+			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;
+
+	switch (cmd) {
+	case ROOTNS_GET_NSFD:
+		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;
+	}
+}
+
+#ifdef CONFIG_COMPAT
+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:
+	case ROOTNS_KILL:
+		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;
+}
+
+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);
+}
+
+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_free;
+	}
+	c->user_ns = user_ns;
+	ns_ref_active_get(user_ns);
+
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
+		ret = -EPERM;
+		goto err_free;
+	}
+
+	ns = create_new_namespaces(clone_flags, current->nsproxy, user_ns,
+				   NULL);
+	if (IS_ERR(ns)) {
+		ret = PTR_ERR(ns);
+		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_free:
+	free_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;
+}
+
+/**
+ * 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 = security_rootns_clone(rootns);
+	if (ret)
+		return ret;
+
+	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/sys_ni.c b/kernel/sys_ni.c
index c8be0abaa40778..9fba98f15a2069 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);
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbacef9..3bea8664719169 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;
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0ab5316051202e..b6d1b033f49ab2 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
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46b8..56b515b20812cb 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 4727b8347fc4e2..919d4bb6370139 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 */
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04bf..7c44f93e57a475 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 00000000000000..62629d112e12f3
--- /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 00000000000000..21b1aecc003b86
--- /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 00000000000000..b690ed71a5211c
--- /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 00000000000000..7594b7a40c0cfe
--- /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 00000000000000..2cb23ca2ad290a
--- /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

3/2 2026/11/24 16:16 llm patch-evaluator
10m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 69401
							output: 17
							thoughts: 739
						

Thoughts:
**Root Namespace Patch Analysis**

Okay, let's dive into this patch and review request. The user has submitted a commit, `5eee798c49d5a9e72c751aa7953598064d617c03`, introducing a completely new `CONFIG_ROOTNS` subsystem. This is a significant undertaking.

Looking at the changes, it's clear this touches *a lot* of core kernel areas: documentation, a new `rootns` syscall, file system code, namespaces, process creation through `fork` and `clone3`, credentials, security hooks, and even selftests. The files modified are:

*   `Documentation/userspace-api/rootns.rst`
*   `arch/*/syscall.tbl`: Adds the `rootns` syscall.
*   `fs/devpts/inode.c`, `fs/filesystems.c`, `fs/fs_context.c`, `fs/fsopen.c`, `fs/namespace.c`, `fs/nsfs.c`, `fs/proc/root.c`
*   `ipc/mqueue.c`
*   `include/linux/rootns.h`, `include/uapi/linux/rootns.h`
*   `kernel/rootns.c`, `kernel/fork.c`, `kernel/nsproxy.c`, `kernel/cred.c`, `kernel/user_namespace.c`
*   `security/security.c`
*   `tools/testing/selftests/rootns/...`

This is a deep integration with VFS, mounts, namespaces, process management, and security. Given the scope and impact on these fundamental subsystems, it's a prime target for fuzzing. *Definitely* worth a deep dive from a fuzzing perspective.

Now, let's ensure we have the right configurations:

1.  `WorthFuzzing`: **Yes** (Confirmed!)
2.  `EnableConfigs`: What do we need to build a fuzzing environment?

I should check `init/Kconfig` for `CONFIG_ROOTNS`.

Okay, so we need `USER_NS`, `PID_NS`, `UTS_NS`, `IPC_NS`, `NET_NS`, and `CGROUPS` enabled. I'll need to double-check that there aren't any hidden dependencies in the Kconfig or other files that might be relevant. I'll use `grepper` or `read-file` to do a thorough check.


4/2 2026/11/24 16:26 tool grepper
0m Args:
{
  "Expression": "config ROOTNS"
}

Results:
{
  "Output": "init/Kconfig=1276=config NET_NS\n--\ninit/Kconfig-1283-\ninit/Kconfig:1284:config ROOTNS\ninit/Kconfig-1285-\tbool \"Root namespace\"\n"
}

5/2 2026/11/24 16:26 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 70784
							output: 33
							thoughts: 15
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Diving into the Kernel Configuration Landscape**

Right, let's get down to brass tacks. I'm thinking about digging into the `init/Kconfig` file, specifically around line 1284. The precise line number isn't super crucial, it's more of a general idea. I'm likely looking for something specific within the initial configuration options. I'm probably trying to understand the configuration space related to boot initialization, potentially related to a particular driver, feature, or subsystem I'm working with. That area of `Kconfig` probably defines a set of options and their dependencies that will either be enabled or disabled at boot time. I'm going to want to understand what the different variables and their definitions are, and how they relate to the underlying code.



6/2 2026/11/24 16:28 tool read-file
0m Args:
{
  "File": "init/Kconfig",
  "FirstLine": 1280,
  "LineCount": 20
}

Results:
{
  "Contents": "1280:\t\thelp\n1281:\t\t  Allow user space to create what appear to be multiple instances\n1282:\t\t  of the network stack.\n1283:\t\n1284:\tconfig ROOTNS\n1285:\t\tbool \"Root namespace\"\n1286:\t\tdepends on USER_NS \u0026\u0026 PID_NS \u0026\u0026 UTS_NS \u0026\u0026 IPC_NS \u0026\u0026 NET_NS \u0026\u0026 CGROUPS\n1287:\t\thelp\n1288:\t\t  Allow user space to create and manage isolated root namespaces\n1289:\t\t  with their own mount tree, user namespace, namespace set, and init\n1290:\t\t  process lifecycle via rootns(), rootns ioctls, and clone3() with\n1291:\t\t  CLONE_INTO_ROOTNS.\n1292:\t\n1293:\tendif # NAMESPACES\n1294:\t\n1295:\tconfig CHECKPOINT_RESTORE\n1296:\t\tbool \"Checkpoint/restore support\"\n1297:\t\tdepends on PROC_FS\n1298:\t\tselect PROC_CHILDREN\n1299:\t\tselect KCMP\n"
}

7/2 2026/11/24 16:28 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 71315
							output: 28
							thoughts: 1532
						

Thoughts:
**Focus Symbol Determination for RootNS Implementation**

Okay, let's break this down. My goal here is to identify the most effective "FocusSymbols" for fuzzing the `rootns` implementation, keeping in mind that these symbols should *not* be ubiquitous functions. First, I need to understand the dependencies and core components of this feature. It's built on a foundation of namespaces: `USER_NS`, `PID_NS`, `UTS_NS`, `IPC_NS`, `NET_NS`, and `CGROUPS`, with an optional `TIME_NS`. The `create_rootns` function, and the `CLONE_NEW...` flags associated with them, are key.

Now, let's analyze the relevant functions. In `kernel/rootns.c`, I see `sys_rootns`, `rootns_ioctl`, `rootns_get_nsfd`, `rootns_wait`, `rootns_kill_members`, `rootns_poll`, `rootns_release`, `copy_rootns`, `exit_rootns`, `rootns_prepare_fork`, `rootns_finish_fork`, and `create_rootns`. In `fs/fsopen.c` I see `fsconfig_set_rootns`, `sys_fsopen`, and `vfs_fsconfig_locked`. `fs/namespace.c` has `move_mount_mntns`, `mnt_ns_get_root`, `do_move_mount`, `attach_recursive_mnt`, `sys_move_mount`, and `sys_fsmount`. Furthermore, `nsproxy_open_namespace` in `fs/nsfs.c`, `proc_set_rootns` in `fs/proc/root.c`, `mqueue_set_rootns` in `ipc/mqueue.c`, `copy_creds` in `kernel/cred.c`, `copy_fs` in `kernel/fork.c`, `install_user_ns_cred` in `kernel/user_namespace.c` and lastly, in `security/security.c`, I see `security_rootns_alloc`, `security_rootns_clone`, and `security_rootns_kill`.

My next step is to sift through this list, keeping in mind the fuzzing rules: avoid ubiquitous functions. Functions like `copy_process`, `kernel_clone`, `copy_creds`, `copy_fs`, and `copy_namespaces` are definitely out; they are called on *every* fork or clone. I need to focus on the functions that are *specific* to `rootns` or related namespace operations.

Here's my refined list of FocusSymbols:

*   `sys_rootns`: This is the direct entrypoint for the new system call, so it's a prime target. I'll need to check the naming convention in `kallsyms` to be sure I'm targeting the right symbol (`sys_rootns` vs. `__se_sys_rootns` or some other variation).
*   `rootns_ioctl`: The dedicated ioctl handler for rootns file descriptors, this is feature-specific logic.
*   `rootns_poll`: The dedicated poll handler for rootns file descriptors, this is feature-specific logic.
*   `rootns_prepare_fork` and `rootns_finish_fork`: These are only called when `CLONE_INTO_ROOTNS` is set. Definitely not ubiquitous, but are part of fork so need to be validated.
*   `fsconfig_set_rootns`: This function sets the rootns and is specific to FSCONFIG_SET_ROOTNS.
*   `move_mount_mntns`: Specific logic for move mount with `MOVE_MOUNT_T_MNTNS` and is specific to the rootns implementation.
*   `nsproxy_open_namespace`: Specific to namespace.
*   `proc_set_rootns`
*   `mqueue_set_rootns`
*   `security_rootns_alloc`
*   `copy_rootns`: Specific to rootns, called in copy process when rootns is set.
*   `exit_rootns`: Specific to rootns, called when pid_ns processes are zapped.

Finally, I need to cross-reference these symbols with how Syzkaller actually targets them – that is, what symbol names are present in `kallsyms`. This final check will make sure that the fuzzer can correctly find these entry points.



8/2 2026/11/24 16:30 tool grepper
0m Args:
{
  "Expression": "__do_sys_",
  "PathPrefixes": [
    "kernel/"
  ]
}

Results:
{
  "Output": "no matches"
}

9/2 2026/11/24 16:30 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 73872
							output: 33
							thoughts: 250
						

Thoughts:
**My Analysis of the Root Namespace System Call**

Okay, so I'm diving into this root namespace system call, and the first thing that's hitting me is the sheer *variety* of function names generated by `SYSCALL_DEFINE`. It's architecture-dependent, and that's the first thing that strikes me as worth noting. I see `__do_sys_foo`, `__se_sys_foo`, `sys_foo` for generic calls, but in x86 I'm finding `__x64_sys_rootns` or `sys_rootns` or even `__do_sys_rootns`. Okay, so `SYSCALL_DEFINE1(rootns, unsigned int, flags)` defines the core call `sys_rootns` which is declared as `asmlinkage long sys_rootns(unsigned int flags);` in `include/linux/syscalls.h`.

But it doesn't stop there, does it? I'm seeing a whole family of functions related to root namespaces: `rootns_ioctl`, `rootns_poll`, `rootns_prepare_fork`, `rootns_finish_fork`, `fsconfig_set_rootns`, `move_mount_mntns`, `nsproxy_open_namespace`, `exit_rootns`, `copy_rootns`, `create_rootns`. It's a whole ecosystem of functionality. I need to understand the relationships and scoping here.

Alright, a deeper dive into `kernel/rootns.c` is the next obvious step. I'm going to determine which functions are static—meaning they are internal to that module—and which ones are global or exported. This will paint a clearer picture of the API surface and how the kernel interacts with the root namespace functionality. This static versus non-static distinction is crucial for understanding how the system call interacts with the internal workings of the kernel.



10/2 2026/11/24 16:31 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 1,
  "LineCount": 100
}

Results:
{
  "Contents": "   1:\t// SPDX-License-Identifier: GPL-2.0-only\n   2:\t/*\n   3:\t * Copyright (C) 2017-2019 Red Hat, Inc. All Rights Reserved.\n   4:\t */\n   5:\t\n   6:\t/**\n   7:\t * DOC: Overview\n   8:\t *\n   9:\t * A root namespace binds a full set of detached namespaces, an initially empty\n  10:\t * mount namespace, an owning user namespace, and an init process behind a\n  11:\t * pollable control file descriptor:\n  12:\t *\n  13:\t * 1. ``rootns()`` allocates a detached ``rootns`` with a fresh user namespace\n  14:\t *    and dedicated mount (``CLONE_EMPTY_MNTNS``), PID, UTS, IPC, network,\n  15:\t *    cgroup, and time namespaces, returning its control fd.\n  16:\t *\n  17:\t * 2. Userspace configures superblocks via ``FSCONFIG_SET_ROOTNS``, retrieves\n  18:\t *    the mount namespace fd via ``ioctl(rootnsfd, ROOTNS_GET_NSFD,\n  19:\t *    CLONE_NEWNS)``, and installs ``\"/\"`` and relative submounts via\n  20:\t *    ``MOVE_MOUNT_T_MNTNS``.\n  21:\t *\n  22:\t * 3. ``clone3()`` with ``CLONE_INTO_ROOTNS`` spawns processes into the\n  23:\t *    ``rootns``; the first call commits PID 1 while concurrent bootstrap\n  24:\t *    callers wait killably.\n  25:\t *\n  26:\t * 4. ``ioctl(rootnsfd, ROOTNS_KILL, sig)`` signals all member thread groups.\n  27:\t *    When PID 1 exits, the PID namespace zaps and reaps all remaining tasks,\n  28:\t *    ``poll()`` reports ``EPOLLHUP``, and ``ioctl(rootnsfd, ROOTNS_WAIT,\n  29:\t *    \u0026args)`` returns init's exit status.\n  30:\t */\n  31:\t\n  32:\t#include \u003clinux/poll.h\u003e\n  33:\t#include \u003clinux/wait.h\u003e\n  34:\t#include \u003cuapi/linux/wait.h\u003e\n  35:\t#include \u003clinux/file.h\u003e\n  36:\t#include \u003clinux/fs.h\u003e\n  37:\t#include \u003clinux/fs_struct.h\u003e\n  38:\t#include \u003clinux/anon_inodes.h\u003e\n  39:\t#include \u003clinux/rootns.h\u003e\n  40:\t#include \u003clinux/sched/signal.h\u003e\n  41:\t#include \u003clinux/sched/task.h\u003e\n  42:\t#include \u003clinux/slab.h\u003e\n  43:\t#include \u003clinux/syscalls.h\u003e\n  44:\t#include \u003clinux/uaccess.h\u003e\n  45:\t#include \u003clinux/mnt_namespace.h\u003e\n  46:\t#include \u003clinux/nsproxy.h\u003e\n  47:\t#include \u003clinux/ns_common.h\u003e\n  48:\t#include \u003clinux/nsfs.h\u003e\n  49:\t#include \u003clinux/pid.h\u003e\n  50:\t#include \u003clinux/pid_namespace.h\u003e\n  51:\t#include \u003clinux/time_namespace.h\u003e\n  52:\t#include \u003clinux/user_namespace.h\u003e\n  53:\t#include \u003clinux/compat.h\u003e\n  54:\t#include \u003clinux/idr.h\u003e\n  55:\t#include \u003clinux/security.h\u003e\n  56:\t#include \u003cuapi/linux/rootns.h\u003e\n  57:\t\n  58:\t/*\n  59:\t * Get a reference to a rootns.\n  60:\t */\n  61:\tstruct rootns *get_rootns(struct rootns *c)\n  62:\t{\n  63:\t\trefcount_inc(\u0026c-\u003eusage);\n  64:\t\treturn c;\n  65:\t}\n  66:\t\n  67:\tstatic void free_rootns(struct rootns *c)\n  68:\t{\n  69:\t\tif (c-\u003ens)\n  70:\t\t\tput_nsproxy(c-\u003ens);\n  71:\t\tif (c-\u003einit_pid)\n  72:\t\t\tput_pid(c-\u003einit_pid);\n  73:\t\tif (c-\u003euser_ns) {\n  74:\t\t\tns_ref_active_put(c-\u003euser_ns);\n  75:\t\t\tput_user_ns(c-\u003euser_ns);\n  76:\t\t}\n  77:\t\tkfree(c);\n  78:\t}\n  79:\t\n  80:\t/*\n  81:\t * Drop a reference on a rootns and clear it if it is no longer in use.\n  82:\t */\n  83:\tvoid put_rootns(struct rootns *c)\n  84:\t{\n  85:\t\tif (!c || !refcount_dec_and_test(\u0026c-\u003eusage))\n  86:\t\t\treturn;\n  87:\t\n  88:\t\tsecurity_rootns_free(c);\n  89:\t\tfree_rootns(c);\n  90:\t}\n  91:\t\n  92:\t/*\n  93:\t * Allow the user to poll for the rootns dying.\n  94:\t */\n  95:\tstatic __poll_t rootns_poll(struct file *file, poll_table *wait)\n  96:\t{\n  97:\t\tstruct rootns *rootns = file-\u003eprivate_data;\n  98:\t\t__poll_t mask = 0;\n  99:\t\n 100:\t\tpoll_wait(file, \u0026rootns-\u003ewaitq, wait);\n"
}

11/2 2026/11/24 16:31 llm patch-evaluator
2m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 76062
							output: 35
							thoughts: 14
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Diving into `kernel/rootns.c`**

Alright, let's dig into `kernel/rootns.c`. I'm starting here because I have a hunch this is where the core of the root namespace implementation is likely to reside. Given my understanding of how namespaces operate in the Linux kernel, I expect to see the primary data structures that define a root namespace, along with the key functions involved in its creation, destruction, and interaction with other namespaces. I'm looking for the nitty-gritty details of how root namespace membership is managed. Specifically, I'm interested in how it ties into mount namespaces and potentially user namespaces – I suspect there's a delicate dance happening there. Let's see how they deal with the lifecycle of the root namespace and how changes are reflected system-wide. I'll be keeping an eye out for any interactions with the VFS or other critical subsystems, as I would expect to see the standard operations like initialization, cleanup, and security checks. It's time to get a clear picture of how this component fits into the grand scheme of things.



12/2 2026/11/24 16:33 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 101,
  "LineCount": 100
}

Results:
{
  "Contents": " 101:\t\n 102:\t\tif (READ_ONCE(rootns-\u003estate) == ROOTNS_DEAD)\n 103:\t\t\tmask |= EPOLLHUP;\n 104:\t\n 105:\t\treturn mask;\n 106:\t}\n 107:\t\n 108:\tstatic long rootns_get_nsfd(struct rootns *rootns, unsigned long nstype)\n 109:\t{\n 110:\t\tif (nstype \u003e UINT_MAX)\n 111:\t\t\treturn -EINVAL;\n 112:\t\tif (!ns_capable(rootns-\u003euser_ns, CAP_SYS_ADMIN))\n 113:\t\t\treturn -EPERM;\n 114:\t\n 115:\t\tif (nstype == CLONE_NEWPID) {\n 116:\t\t\tif (!pidns_is_ancestor(rootns-\u003ens-\u003epid_ns_for_children,\n 117:\t\t\t\t\t       task_active_pid_ns(current)))\n 118:\t\t\t\treturn -EXDEV;\n 119:\t\t\tif (READ_ONCE(rootns-\u003estate) != ROOTNS_RUNNING)\n 120:\t\t\t\treturn -ESRCH;\n 121:\t\t}\n 122:\t\n 123:\t\treturn nsproxy_open_namespace(rootns-\u003ens, rootns-\u003euser_ns, nstype);\n 124:\t}\n 125:\t\n 126:\tstatic long rootns_wait(struct rootns *rootns, void __user *uarg)\n 127:\t{\n 128:\t\tstruct pid_namespace *pid_ns = task_active_pid_ns(current);\n 129:\t\tstruct rootns_wait_args args;\n 130:\t\tlong ret;\n 131:\t\n 132:\t\tif (!uarg)\n 133:\t\t\treturn -EINVAL;\n 134:\t\tif (copy_from_user(\u0026args, uarg, sizeof(args)))\n 135:\t\t\treturn -EFAULT;\n 136:\t\tif (args.flags \u0026 ~WNOHANG)\n 137:\t\t\treturn -EINVAL;\n 138:\t\tif (READ_ONCE(rootns-\u003estate) == ROOTNS_INIT)\n 139:\t\t\treturn -ECHILD;\n 140:\t\n 141:\t\tif (!(args.flags \u0026 WNOHANG)) {\n 142:\t\t\tret = wait_event_freezable(rootns-\u003ewaitq,\n 143:\t\t\t\t\t\t   READ_ONCE(rootns-\u003estate) == ROOTNS_DEAD ||\n 144:\t\t\t\t\t\t   READ_ONCE(rootns-\u003estate) == ROOTNS_INIT);\n 145:\t\t\tif (ret)\n 146:\t\t\t\treturn ret;\n 147:\t\t}\n 148:\t\n 149:\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n 150:\t\t\tif (rootns-\u003estate == ROOTNS_INIT)\n 151:\t\t\t\treturn -ECHILD;\n 152:\t\t\tif (rootns-\u003estate != ROOTNS_DEAD)\n 153:\t\t\t\treturn 0;\n 154:\t\t\tret = pid_nr_ns(rootns-\u003einit_pid, pid_ns);\n 155:\t\t\tif (ret \u003c= 0)\n 156:\t\t\t\treturn -ECHILD;\n 157:\t\t\targs.status = rootns-\u003eexit_code;\n 158:\t\t}\n 159:\t\n 160:\t\tif (copy_to_user(uarg, \u0026args, sizeof(args)))\n 161:\t\t\treturn -EFAULT;\n 162:\t\treturn ret;\n 163:\t}\n 164:\t\n 165:\tstatic int rootns_kill_members(struct rootns *rootns, int sig)\n 166:\t{\n 167:\t\tstruct pid_namespace *pid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n 168:\t\tbool any_success = false;\n 169:\t\tbool any_other = false;\n 170:\t\tbool any_perm = false;\n 171:\t\tint other_err = 0;\n 172:\t\tstruct pid *pid;\n 173:\t\tint ret;\n 174:\t\tint nr;\n 175:\t\n 176:\t\tif (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))\n 177:\t\t\treturn -EXDEV;\n 178:\t\tif (READ_ONCE(rootns-\u003estate) != ROOTNS_RUNNING)\n 179:\t\t\treturn -ESRCH;\n 180:\t\n 181:\t\tret = security_rootns_kill(rootns, sig);\n 182:\t\tif (ret)\n 183:\t\t\treturn ret;\n 184:\t\n 185:\t\tscoped_guard(rcu) {\n 186:\t\t\tread_lock(\u0026tasklist_lock);\n 187:\t\t\tidr_for_each_entry(\u0026pid_ns-\u003eidr, pid, nr) {\n 188:\t\t\t\tstruct task_struct *task = pid_task(pid, PIDTYPE_TGID);\n 189:\t\t\t\tint err;\n 190:\t\n 191:\t\t\t\tif (!task)\n 192:\t\t\t\t\tcontinue;\n 193:\t\n 194:\t\t\t\terr = group_send_sig_info(sig, SEND_SIG_NOINFO, task,\n 195:\t\t\t\t\t\t\t  PIDTYPE_MAX);\n 196:\t\t\t\tif (!err) {\n 197:\t\t\t\t\tany_success = true;\n 198:\t\t\t\t} else if (err == -EPERM) {\n 199:\t\t\t\t\tany_perm = true;\n 200:\t\t\t\t} else if (err != -ESRCH \u0026\u0026 !any_other) {\n"
}

13/2 2026/11/24 16:33 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 77882
							output: 35
							thoughts: 14
						

Thoughts:
Okay, here's my interpretation of what's going on, formatted as you requested:

**Delving into `kernel/rootns.c`**

Alright, let's dive into the `kernel/rootns.c` file. I need to get a better handle on how the root namespace is managed within the kernel. I'm already pretty familiar with the general namespace concepts, but I need to see the specifics of how the root namespace interacts with everything else. I'm expecting this file to have the core functions for creating, destroying, and manipulating the root namespace. I anticipate seeing the data structures used to represent the namespace, particularly how it links to mount points and processes. I'm also looking for the initial setup sequence – how the root namespace is initialized when the kernel boots. I'm especially interested in how it interacts with the initial PID namespace. I'm keen to see the details of namespace propagation when a new root namespace is created via clone(), and how that affects mount namespaces. Let's see if this code confirms my hypotheses and reveals anything new. I'm ready to get my hands dirty.



14/2 2026/11/24 16:34 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 201,
  "LineCount": 100
}

Results:
{
  "Contents": " 201:\t\t\t\t\tany_other = true;\n 202:\t\t\t\t\tother_err = err;\n 203:\t\t\t\t}\n 204:\t\t\t}\n 205:\t\t\tread_unlock(\u0026tasklist_lock);\n 206:\t\t}\n 207:\t\n 208:\t\tif (any_success)\n 209:\t\t\treturn 0;\n 210:\t\tif (any_other)\n 211:\t\t\treturn other_err;\n 212:\t\tif (any_perm)\n 213:\t\t\treturn -EPERM;\n 214:\t\treturn -ESRCH;\n 215:\t}\n 216:\t\n 217:\tstatic long rootns_ioctl(struct file *file, unsigned int cmd, unsigned long arg)\n 218:\t{\n 219:\t\tstruct rootns *rootns = file-\u003eprivate_data;\n 220:\t\n 221:\t\tswitch (cmd) {\n 222:\t\tcase ROOTNS_GET_NSFD:\n 223:\t\t\treturn rootns_get_nsfd(rootns, arg);\n 224:\t\tcase ROOTNS_WAIT:\n 225:\t\t\treturn rootns_wait(rootns, (void __user *)arg);\n 226:\t\tcase ROOTNS_KILL:\n 227:\t\t\tif (arg \u003e INT_MAX || !valid_signal(arg))\n 228:\t\t\t\treturn -EINVAL;\n 229:\t\t\treturn rootns_kill_members(rootns, arg);\n 230:\t\tdefault:\n 231:\t\t\treturn -ENOIOCTLCMD;\n 232:\t\t}\n 233:\t}\n 234:\t\n 235:\t#ifdef CONFIG_COMPAT\n 236:\tstatic long rootns_compat_ioctl(struct file *file, unsigned int cmd,\n 237:\t\t\t\t\tunsigned long arg)\n 238:\t{\n 239:\t\tswitch (cmd) {\n 240:\t\tcase ROOTNS_WAIT:\n 241:\t\t\treturn rootns_ioctl(file, cmd, (unsigned long)compat_ptr(arg));\n 242:\t\tcase ROOTNS_GET_NSFD:\n 243:\t\tcase ROOTNS_KILL:\n 244:\t\t\treturn rootns_ioctl(file, cmd, arg);\n 245:\t\tdefault:\n 246:\t\t\treturn -ENOIOCTLCMD;\n 247:\t\t}\n 248:\t}\n 249:\t#endif\n 250:\t\n 251:\tstatic int __rootns_kill(struct rootns *rootns, int sig, bool priv)\n 252:\t{\n 253:\t\tstruct pid *pid = NULL;\n 254:\t\tint ret;\n 255:\t\n 256:\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n 257:\t\t\tif (rootns-\u003estate == ROOTNS_RUNNING)\n 258:\t\t\t\tpid = get_pid(rootns-\u003einit_pid);\n 259:\t\t}\n 260:\t\tif (!pid)\n 261:\t\t\treturn -ESRCH;\n 262:\t\n 263:\t\tret = kill_pid(pid, sig, priv);\n 264:\t\tput_pid(pid);\n 265:\t\treturn ret;\n 266:\t}\n 267:\t\n 268:\tstatic int rootns_release(struct inode *inode, struct file *file)\n 269:\t{\n 270:\t\tstruct rootns *rootns = file-\u003eprivate_data;\n 271:\t\n 272:\t\tif (rootns-\u003eflags \u0026 ROOTNS_KILL_ON_CLOSE)\n 273:\t\t\t__rootns_kill(rootns, SIGKILL, true);\n 274:\t\tput_rootns(rootns);\n 275:\t\treturn 0;\n 276:\t}\n 277:\t\n 278:\tstatic const struct file_operations rootns_fops = {\n 279:\t\t.poll\t\t= rootns_poll,\n 280:\t\t.unlocked_ioctl\t= rootns_ioctl,\n 281:\t#ifdef CONFIG_COMPAT\n 282:\t\t.compat_ioctl\t= rootns_compat_ioctl,\n 283:\t#endif\n 284:\t\t.release\t= rootns_release,\n 285:\t};\n 286:\t\n 287:\t/*\n 288:\t * Returns true if the file is a rootns.\n 289:\t */\n 290:\tbool is_rootns_file(struct file *file)\n 291:\t{\n 292:\t\treturn file-\u003ef_op == \u0026rootns_fops;\n 293:\t}\n 294:\t\n 295:\tvoid copy_rootns(struct task_struct *tsk, struct pid *pid, struct rootns *c)\n 296:\t{\n 297:\t\tif (likely(!c || !is_child_reaper(pid)))\n 298:\t\t\treturn;\n 299:\t\n 300:\t\tscoped_guard(spinlock, \u0026c-\u003elock) {\n"
}

15/2 2026/11/24 16:34 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 79516
							output: 35
							thoughts: 14
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Diving into `kernel/rootns.c`**

Alright, let's dig into `kernel/rootns.c`. I'm starting here because I have a hunch this is where the core of the root namespace implementation is likely to reside. Given my understanding of how namespaces operate in the Linux kernel, I expect to see the primary data structures that define a root namespace, along with the key functions involved in its creation, destruction, and interaction with other namespaces. I'm looking for the nitty-gritty details of how root namespace membership is managed. Specifically, I'm interested in how it ties into mount namespaces and potentially user namespaces – I suspect there's a delicate dance happening there. Let's see how they deal with the lifecycle of the root namespace and how changes are reflected system-wide. I'll be keeping an eye out for any interactions with the VFS or other critical subsystems, as I would expect to see the standard operations like initialization, cleanup, and security checks. It's time to get a clear picture of how this component fits into the grand scheme of things.



16/2 2026/11/24 16:34 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 301,
  "LineCount": 100
}

Results:
{
  "Contents": " 301:\t\t\tif (c-\u003estate != ROOTNS_FORKING)\n 302:\t\t\t\treturn;\n 303:\t\t\tns_of_pid(pid)-\u003erootns = get_rootns(c);\n 304:\t\t\tWRITE_ONCE(c-\u003einit_pid, get_pid(pid));\n 305:\t\t\tWRITE_ONCE(c-\u003estate, ROOTNS_RUNNING);\n 306:\t\t}\n 307:\t\twake_up_all(\u0026c-\u003ewaitq);\n 308:\t}\n 309:\t\n 310:\tvoid exit_rootns(struct pid_namespace *pid_ns, struct task_struct *tsk)\n 311:\t{\n 312:\t\tstruct rootns *c = pid_ns-\u003erootns;\n 313:\t\tstruct task_struct *leader;\n 314:\t\tint status;\n 315:\t\n 316:\t\tif (!c)\n 317:\t\t\treturn;\n 318:\t\n 319:\t\tleader = tsk-\u003egroup_leader;\n 320:\t\tstatus = (tsk-\u003esignal-\u003eflags \u0026 SIGNAL_GROUP_EXIT) ?\n 321:\t\t\t tsk-\u003esignal-\u003egroup_exit_code : leader-\u003eexit_code;\n 322:\t\n 323:\t\tscoped_guard(spinlock, \u0026c-\u003elock) {\n 324:\t\t\tc-\u003eexit_code = status;\n 325:\t\t\tWRITE_ONCE(c-\u003estate, ROOTNS_DEAD);\n 326:\t\t}\n 327:\t\n 328:\t\tpid_ns-\u003erootns = NULL;\n 329:\t\twake_up_poll(\u0026c-\u003ewaitq, EPOLLHUP);\n 330:\t\tput_rootns(c);\n 331:\t}\n 332:\t\n 333:\tstatic struct user_namespace *create_rootns_user_ns(void)\n 334:\t{\n 335:\t\tstruct user_namespace *user_ns;\n 336:\t\tstruct cred *new;\n 337:\t\tint ret;\n 338:\t\n 339:\t\tnew = prepare_creds();\n 340:\t\tif (!new)\n 341:\t\t\treturn ERR_PTR(-ENOMEM);\n 342:\t\n 343:\t\tret = create_user_ns(new);\n 344:\t\tif (ret \u003c 0) {\n 345:\t\t\tabort_creds(new);\n 346:\t\t\treturn ERR_PTR(ret);\n 347:\t\t}\n 348:\t\n 349:\t\tuser_ns = get_user_ns(new-\u003euser_ns);\n 350:\t\tabort_creds(new);\n 351:\t\treturn user_ns;\n 352:\t}\n 353:\t\n 354:\t/*\n 355:\t * Create a new rootns.\n 356:\t */\n 357:\tstatic struct rootns *create_rootns(unsigned int flags)\n 358:\t{\n 359:\t\tu64 clone_flags = CLONE_NEWNS | CLONE_EMPTY_MNTNS | CLONE_NEWPID |\n 360:\t\t\t\t  CLONE_NEWCGROUP | CLONE_NEWUTS | CLONE_NEWIPC |\n 361:\t\t\t\t  CLONE_NEWNET |\n 362:\t\t\t\t  (IS_ENABLED(CONFIG_TIME_NS) ? CLONE_NEWTIME : 0);\n 363:\t\tstruct user_namespace *user_ns;\n 364:\t\tstruct nsproxy *ns;\n 365:\t\tstruct rootns *c;\n 366:\t\tint ret;\n 367:\t\n 368:\t\tc = kzalloc_obj(*c, GFP_KERNEL);\n 369:\t\tif (!c)\n 370:\t\t\treturn ERR_PTR(-ENOMEM);\n 371:\t\n 372:\t\tinit_waitqueue_head(\u0026c-\u003ewaitq);\n 373:\t\tspin_lock_init(\u0026c-\u003elock);\n 374:\t\trefcount_set(\u0026c-\u003eusage, 1);\n 375:\t\tc-\u003eflags = flags;\n 376:\t\n 377:\t\tuser_ns = create_rootns_user_ns();\n 378:\t\tif (IS_ERR(user_ns)) {\n 379:\t\t\tret = PTR_ERR(user_ns);\n 380:\t\t\tgoto err_free;\n 381:\t\t}\n 382:\t\tc-\u003euser_ns = user_ns;\n 383:\t\tns_ref_active_get(user_ns);\n 384:\t\n 385:\t\tif (!ns_capable(user_ns, CAP_SYS_ADMIN)) {\n 386:\t\t\tret = -EPERM;\n 387:\t\t\tgoto err_free;\n 388:\t\t}\n 389:\t\n 390:\t\tns = create_new_namespaces(clone_flags, current-\u003ensproxy, user_ns,\n 391:\t\t\t\t\t   NULL);\n 392:\t\tif (IS_ERR(ns)) {\n 393:\t\t\tret = PTR_ERR(ns);\n 394:\t\t\tgoto err_free;\n 395:\t\t}\n 396:\t\n 397:\t\ttimens_activate_nsproxy(ns);\n 398:\t\tc-\u003ens = ns;\n 399:\t\tnsproxy_ns_active_get(ns);\n 400:\t\n"
}

17/2 2026/11/24 16:34 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 81253
							output: 35
							thoughts: 15
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Diving into the Details: Lines 401-500**

Alright, let's get down to brass tacks. I've been working through this section, and my immediate instinct is to focus on lines 401-500. It's time to dig in and really see what's being laid out here. I'm approaching this with a critical eye, as always. Let's see if the author's arguments hold water, if the methodology is sound, and if the conclusions logically follow from the presented evidence. I'm anticipating some potentially nuanced points in this segment, and I'm ready to parse them meticulously. Time to sift through the data and see what gems this section might yield.



18/2 2026/11/24 16:35 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 401,
  "LineCount": 100
}

Results:
{
  "Contents": " 401:\t\tret = security_rootns_alloc(c, flags);\n 402:\t\tif (ret \u003c 0)\n 403:\t\t\tgoto err_free;\n 404:\t\n 405:\t\treturn c;\n 406:\t\n 407:\terr_free:\n 408:\t\tfree_rootns(c);\n 409:\t\treturn ERR_PTR(ret);\n 410:\t}\n 411:\t\n 412:\t/**\n 413:\t * sys_rootns - Create a detached root namespace\n 414:\t * @flags: Combination of \u0026enum rootns_flags values\n 415:\t *\n 416:\t * Allocate a detached root namespace owning a fresh user namespace and\n 417:\t * dedicated empty mount, PID, UTS, IPC, network, cgroup, and time namespaces.\n 418:\t *\n 419:\t * Return: Control file descriptor on success, negative error code on failure.\n 420:\t */\n 421:\tSYSCALL_DEFINE1(rootns, unsigned int, flags)\n 422:\t{\n 423:\t\tstruct rootns *c;\n 424:\t\tint fd;\n 425:\t\n 426:\t\tif (flags \u0026 ~ROOTNS_ALL_FLAGS)\n 427:\t\t\treturn -EINVAL;\n 428:\t\tif (unlikely(!current-\u003ensproxy))\n 429:\t\t\treturn -EOPNOTSUPP;\n 430:\t\n 431:\t\tc = create_rootns(flags);\n 432:\t\tif (IS_ERR(c))\n 433:\t\t\treturn PTR_ERR(c);\n 434:\t\n 435:\t\tfd = anon_inode_getfd(\"rootns\", \u0026rootns_fops, c,\n 436:\t\t\t\t      O_RDWR | (flags \u0026 ROOTNS_CLOSE_ON_EXEC ? O_CLOEXEC : 0));\n 437:\t\tif (fd \u003c 0)\n 438:\t\t\tput_rootns(c);\n 439:\t\n 440:\t\treturn fd;\n 441:\t}\n 442:\t\n 443:\t/**\n 444:\t * DOC: CLONE_INTO_ROOTNS\n 445:\t *\n 446:\t * Passing ``CLONE_INTO_ROOTNS`` in ``struct clone_args.flags`` (with\n 447:\t * ``size \u003e= CLONE_ARGS_SIZE_VER3``) spawns the child process into the root\n 448:\t * namespace identified by ``struct clone_args.rootns``.\n 449:\t *\n 450:\t * Once ``\"/\"`` is mounted in the root namespace's mount namespace, the first\n 451:\t * caller transitions the ``rootns`` from ``ROOTNS_INIT`` through\n 452:\t * ``ROOTNS_FORKING`` to ``ROOTNS_RUNNING`` as PID 1 of its PID namespace\n 453:\t * while concurrent bootstrap callers wait killably. Subsequent callers join\n 454:\t * the running PID namespace until teardown begins.\n 455:\t *\n 456:\t * The caller must hold ``CAP_SYS_ADMIN`` and ``CAP_SYS_CHROOT`` in the target\n 457:\t * user namespace (and ``CAP_SYS_CHROOT`` in its current user namespace when\n 458:\t * chrooted) and run in an ancestor active PID namespace. The child inherits\n 459:\t * the caller's credentials and switches to the target user namespace.\n 460:\t *\n 461:\t * ``CLONE_INTO_ROOTNS`` may be combined with the following ``CLONE_*`` flags:\n 462:\t *\n 463:\t * - ``CLONE_VFORK``\n 464:\t * - ``CLONE_PIDFD``\n 465:\t * - ``CLONE_PIDFD_AUTOKILL``\n 466:\t * - ``CLONE_AUTOREAP``\n 467:\t * - ``CLONE_CLEAR_SIGHAND``\n 468:\t * - ``CLONE_INTO_CGROUP``\n 469:\t * - ``CLONE_NNP``\n 470:\t *\n 471:\t * Returns ``-EBADF`` if ``rootns`` is not an open file descriptor, ``-EINVAL``\n 472:\t * for unsupported flags, invalid argument size, or non-``rootns`` file\n 473:\t * descriptors, ``-ENOENT`` before ``\"/\"`` is installed, ``-EXDEV`` if the\n 474:\t * caller's active PID namespace is not an ancestor, ``-EPERM`` without\n 475:\t * required capabilities, ``-EBUSY`` if the PID\n 476:\t * namespace already has an external init process, and ``-ESRCH`` once teardown\n 477:\t * has started.\n 478:\t */\n 479:\tint rootns_prepare_fork(struct kernel_clone_args *args)\n 480:\t{\n 481:\t\tstruct file *file __free(fput) = fget(args-\u003erootns_fd);\n 482:\t\tstruct path root __free(path_put) = {};\n 483:\t\tstruct pid_namespace *pid_ns;\n 484:\t\tbool bootstrapping = false;\n 485:\t\tstruct rootns *rootns;\n 486:\t\tint ret;\n 487:\t\n 488:\t\tif (!file)\n 489:\t\t\treturn -EBADF;\n 490:\t\tif (!is_rootns_file(file))\n 491:\t\t\treturn -EINVAL;\n 492:\t\n 493:\t\trootns = file-\u003eprivate_data;\n 494:\t\tif (!ns_capable(rootns-\u003euser_ns, CAP_SYS_ADMIN) ||\n 495:\t\t    !ns_capable(rootns-\u003euser_ns, CAP_SYS_CHROOT))\n 496:\t\t\treturn -EPERM;\n 497:\t\tif (current_chrooted() \u0026\u0026 !ns_capable(current_user_ns(), CAP_SYS_CHROOT))\n 498:\t\t\treturn -EPERM;\n 499:\t\n 500:\t\tpid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n"
}

19/2 2026/11/24 16:35 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 83127
							output: 34
							thoughts: 15
						

Thoughts:
Okay, here we go...

**Diving into `kernel/rootns.c`**

Alright, time to crack open the rest of `kernel/rootns.c`. I need a deeper dive into how root namespaces are handled within the kernel. I already have a decent grasp of the overall concept, but I'm looking for the specifics, the nitty-gritty details of the implementation. I'm especially interested in the data structures used, the key functions involved in creation, destruction, and most importantly, how the namespace is actually utilized, and interacted with by other kernel subsystems. I want to see how the kernel ensures proper isolation and interaction with other namespaces on the system. I'm expecting to see calls to things related to mount propagation, PID namespaces, network namespaces, and shared memory, all from the perspective of root. Let's see if this code answers some of the questions I have.



20/2 2026/11/24 16:37 tool read-file
0m Args:
{
  "File": "kernel/rootns.c",
  "FirstLine": 501,
  "LineCount": 81
}

Results:
{
  "Contents": " 501:\t\tif (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))\n 502:\t\t\treturn -EXDEV;\n 503:\t\n 504:\t\tret = security_rootns_clone(rootns);\n 505:\t\tif (ret)\n 506:\t\t\treturn ret;\n 507:\t\n 508:\t\tret = mnt_ns_get_root(rootns-\u003ens-\u003emnt_ns, \u0026root);\n 509:\t\tif (ret)\n 510:\t\t\treturn ret;\n 511:\t\n 512:\t\tfor (;;) {\n 513:\t\t\tbool wait = false;\n 514:\t\n 515:\t\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n 516:\t\t\t\tswitch (rootns-\u003estate) {\n 517:\t\t\t\tcase ROOTNS_INIT:\n 518:\t\t\t\t\tif (READ_ONCE(pid_ns-\u003echild_reaper))\n 519:\t\t\t\t\t\treturn -EBUSY;\n 520:\t\t\t\t\tif (!(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n 521:\t\t\t\t\t\treturn -ESRCH;\n 522:\t\t\t\t\tWRITE_ONCE(rootns-\u003estate, ROOTNS_FORKING);\n 523:\t\t\t\t\tbootstrapping = true;\n 524:\t\t\t\t\tbreak;\n 525:\t\t\t\tcase ROOTNS_FORKING:\n 526:\t\t\t\t\twait = true;\n 527:\t\t\t\t\tbreak;\n 528:\t\t\t\tcase ROOTNS_RUNNING:\n 529:\t\t\t\t\tif (!(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n 530:\t\t\t\t\t\treturn -ESRCH;\n 531:\t\t\t\t\tbreak;\n 532:\t\t\t\tcase ROOTNS_DEAD:\n 533:\t\t\t\t\treturn -ESRCH;\n 534:\t\t\t\t}\n 535:\t\t\t}\n 536:\t\t\tif (!wait)\n 537:\t\t\t\tbreak;\n 538:\t\n 539:\t\t\tret = wait_event_killable(rootns-\u003ewaitq,\n 540:\t\t\t\t\t\t  READ_ONCE(rootns-\u003estate) != ROOTNS_FORKING);\n 541:\t\t\tif (ret)\n 542:\t\t\t\treturn ret;\n 543:\t\t}\n 544:\t\n 545:\t\targs-\u003erootns_file = no_free_ptr(file);\n 546:\t\targs-\u003erootns = rootns;\n 547:\t\targs-\u003erootns_bootstrapping = bootstrapping;\n 548:\t\treturn 0;\n 549:\t}\n 550:\t\n 551:\tint rootns_finish_fork(struct kernel_clone_args *args, struct task_struct *p)\n 552:\t{\n 553:\t\tstruct file *file __free(fput) = args-\u003erootns_file;\n 554:\t\tstruct rootns *rootns = args-\u003erootns;\n 555:\t\tstruct pid_namespace *pid_ns = rootns-\u003ens-\u003epid_ns_for_children;\n 556:\t\tint ret;\n 557:\t\n 558:\t\targs-\u003erootns_file = NULL;\n 559:\t\targs-\u003erootns = NULL;\n 560:\t\tif (!IS_ERR(p)) {\n 561:\t\t\tif (current-\u003ensproxy-\u003etime_ns != rootns-\u003ens-\u003etime_ns)\n 562:\t\t\t\ttimens_commit(p, rootns-\u003ens-\u003etime_ns);\n 563:\t\t\treturn 0;\n 564:\t\t}\n 565:\t\n 566:\t\tret = PTR_ERR(p);\n 567:\t\tif (args-\u003erootns_bootstrapping) {\n 568:\t\t\tscoped_guard(spinlock, \u0026rootns-\u003elock) {\n 569:\t\t\t\tif (rootns-\u003estate == ROOTNS_FORKING)\n 570:\t\t\t\t\tWRITE_ONCE(rootns-\u003estate, ROOTNS_INIT);\n 571:\t\t\t}\n 572:\t\t\twake_up_all(\u0026rootns-\u003ewaitq);\n 573:\t\t\tif (ret == -EINVAL \u0026\u0026 !args-\u003eset_tid_size)\n 574:\t\t\t\tret = -EBUSY;\n 575:\t\t}\n 576:\t\tif ((ret == -ENOMEM || ret == -EBUSY) \u0026\u0026\n 577:\t\t    !(READ_ONCE(pid_ns-\u003epid_allocated) \u0026 PIDNS_ADDING))\n 578:\t\t\treturn -ESRCH;\n 579:\t\n 580:\t\treturn ret;\n 581:\t}\n"
}

21/2 2026/11/24 16:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 84575
							output: 32
							thoughts: 117
						

Thoughts:
Okay, let's dive into this.

**Navigating the Filesystem Namespace Code**

Right, so I'm thinking, let's start by getting a handle on `fs/fsopen.c`, specifically focusing on how `fsconfig_set_rootns` is used. My initial thought is to trace the execution. Hmm, `fsconfig_set_rootns` is declared `static`, which is helpful, but it's only called from `vfs_fsconfig_locked`. That makes sense; it's likely a helper function. And the `fsconfig` syscall, as expected, ultimately calls `vfs_fsconfig_locked`.

Now, the core of this seems to be around `fsconfig_set_rootns`, but I also want to cross-reference with `fs/namespace.c`. I'm specifically curious about how `move_mount_mntns` fits into this picture. I'll need to check the surrounding lines in that file to understand the broader context around `move_mount_mntns`, as I can't just isolate it.



22/2 2026/11/24 16:37 tool grepper
0m Args:
{
  "Expression": "move_mount_mntns",
  "PathPrefixes": [
    "fs/namespace.c"
  ]
}

Results:
{
  "Output": "fs/namespace.c=4797=static int lookup_move_mount_from(int from_dfd,\n--\nfs/namespace.c-4840- */\nfs/namespace.c:4841:static int move_mount_mntns(int from_dfd, const char __user *from_pathname,\nfs/namespace.c-4842-\t\t\t    int to_dfd, const char __user *to_pathname,\n--\nfs/namespace.c=4921=SYSCALL_DEFINE5(move_mount,\n--\nfs/namespace.c-4947-\t\t\treturn -EINVAL;\nfs/namespace.c:4948:\t\treturn move_mount_mntns(from_dfd, from_pathname,\nfs/namespace.c-4949-\t\t\t\t\tto_dfd, to_pathname, flags, mflags);\n"
}

23/2 2026/11/24 16:37 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 85178
							output: 33
							thoughts: 462
						

Thoughts:
**Analyzing Root Namespace Symbol Visibility**

Okay, let's break down these namespace functions. My initial goal is to figure out the symbol visibility for some core root namespace functions. I'll start with the obvious ones and then dig deeper.

First, let's confirm the expected behavior for `mnt_ns_get_root` from `fs/namespace.c`. Good, it's non-static. Then `nsproxy_open_namespace` in `fs/nsfs.c` is also non-static.

Okay, let's keep going. `proc_set_rootns` from `fs/proc/root.c` is static, which is what I would expect, and `mqueue_set_rootns` from `ipc/mqueue.c` is also static. And finally, `install_user_ns_cred` from `kernel/user_namespace.c` is non-static.

Now, looking at `kernel/rootns.c`, I see a mix. We have a set of non-static functions: `get_rootns`, `put_rootns`, `is_rootns_file`, `copy_rootns`, `exit_rootns`, and also `sys_rootns`. Ah, `sys_rootns` looks interesting - it's exposed through the `SYSCALL_DEFINE1` macro. There are also `rootns_prepare_fork` and `rootns_finish_fork`. The static counterparts are `rootns_ioctl`, `rootns_poll`, `rootns_release`, `rootns_get_nsfd`, `rootns_wait`, `rootns_kill_members`, and `create_rootns`.

The `sys_rootns` function is the one I want to look at more closely. Since it uses `SYSCALL_DEFINE1`, that's the key. I need to understand how those syscall define macros are translated on x86_64, which symbols are actually generated. I need to grep the kernel sources for either `__do_sys_`, or `__se_sys_`, to determine the exact symbol name.



24/2 2026/11/24 16:37 tool grepper
0m Args:
{
  "Expression": "__x64_sys_",
  "PathPrefixes": [
    "arch/x86"
  ]
}

Results:
{
  "Output": "arch/x86/entry/syscall_64.c=37=static noinline long x64_sys_call(const struct pt_regs *regs, unsigned int nr)\n--\narch/x86/entry/syscall_64.c-40-\t#include \u003casm/syscalls_64.h\u003e\narch/x86/entry/syscall_64.c:41:\tdefault: return __x64_sys_ni_syscall(regs);\narch/x86/entry/syscall_64.c-42-\t}\n--\narch/x86/entry/syscall_64.c=45=static noinline long x32_sys_call(const struct pt_regs *regs, unsigned int nr)\n--\narch/x86/entry/syscall_64.c-49-\t#include \u003casm/syscalls_x32.h\u003e\narch/x86/entry/syscall_64.c:50:\tdefault: return __x64_sys_ni_syscall(regs);\narch/x86/entry/syscall_64.c-51-\t}\n--\narch/x86/entry/syscalls/syscall_64.tbl-7-#\narch/x86/entry/syscalls/syscall_64.tbl:8:# The __x64_sys_*() stubs are created on-the-fly for sys_*() system calls\narch/x86/entry/syscalls/syscall_64.tbl-9-#\n--\narch/x86/entry/vsyscall/vsyscall_64.c=119=static bool __emulate_vsyscall(struct pt_regs *regs, unsigned long address)\n--\narch/x86/entry/vsyscall/vsyscall_64.c-217-\t\t/* this decodes regs-\u003edi and regs-\u003esi on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:218:\t\tret = __x64_sys_gettimeofday(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-219-\t\tbreak;\n--\narch/x86/entry/vsyscall/vsyscall_64.c-222-\t\t/* this decodes regs-\u003edi on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:223:\t\tret = __x64_sys_time(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-224-\t\tbreak;\n--\narch/x86/entry/vsyscall/vsyscall_64.c-230-\t\t/* this decodes regs-\u003edi, regs-\u003esi and regs-\u003edx on its own */\narch/x86/entry/vsyscall/vsyscall_64.c:231:\t\tret = __x64_sys_getcpu(regs);\narch/x86/entry/vsyscall/vsyscall_64.c-232-\t\tregs-\u003edx = orig_dx;\n--\narch/x86/include/asm/syscall_wrapper.h-10-\narch/x86/include/asm/syscall_wrapper.h:11:extern long __x64_sys_ni_syscall(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h-12-extern long __ia32_sys_ni_syscall(const struct pt_regs *regs);\n--\narch/x86/include/asm/syscall_wrapper.h-16- * struct pt_regs *regs as the only argument of the syscall stub(s) named as:\narch/x86/include/asm/syscall_wrapper.h:17: * __x64_sys_*()         - 64-bit native syscall\narch/x86/include/asm/syscall_wrapper.h-18- * __ia32_sys_*()        - 32-bit native syscall or common compat syscall\n--\narch/x86/include/asm/syscall_wrapper.h-33- *\narch/x86/include/asm/syscall_wrapper.h:34: * \u003c__x64_sys_recv\u003e:\t\t\u003c-- syscall with 4 parameters\narch/x86/include/asm/syscall_wrapper.h-35- *\tcallq\t\u003c__fentry__\u003e\n--\narch/x86/include/asm/syscall_wrapper.h-259- */\narch/x86/include/asm/syscall_wrapper.h:260:long __x64_sys_getcpu(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h:261:long __x64_sys_gettimeofday(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h:262:long __x64_sys_time(const struct pt_regs *regs);\narch/x86/include/asm/syscall_wrapper.h-263-\n"
}

25/2 2026/11/24 16:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 87369
							output: 42
							thoughts: 64
						

Thoughts:
Here's my take on those thoughts:

**Analyzing System Call Wrappers for Root Namespace Operations**

Alright, let's dive into this. I need to understand how the system's handling root namespaces, specifically concerning the x86 architecture. I'm going to check out `arch/x86/include/asm/syscall_wrapper.h` to see what's going on with the `__do_sys_rootns` and `__se_sys_rootns` functions (or macros, likely). I'll examine the actual source code and understand how the system calls are being wrapped to interact with and manage the root namespace. Let's see how these are defined and utilized within the system call interface. I want to see how these calls are interacting with the namespace-related system calls.



26/2 2026/11/24 16:38 tool read-file
0m Args:
{
  "File": "arch/x86/include/asm/syscall_wrapper.h",
  "FirstLine": 14,
  "LineCount": 50
}

Results:
{
  "Contents": "  14:\t/*\n  15:\t * Instead of the generic __SYSCALL_DEFINEx() definition, the x86 version takes\n  16:\t * struct pt_regs *regs as the only argument of the syscall stub(s) named as:\n  17:\t * __x64_sys_*()         - 64-bit native syscall\n  18:\t * __ia32_sys_*()        - 32-bit native syscall or common compat syscall\n  19:\t * __ia32_compat_sys_*() - 32-bit compat syscall\n  20:\t * __x64_compat_sys_*()  - 64-bit X32 compat syscall\n  21:\t *\n  22:\t * The registers are decoded according to the ABI:\n  23:\t * 64-bit: RDI, RSI, RDX, R10, R8, R9\n  24:\t * 32-bit: EBX, ECX, EDX, ESI, EDI, EBP\n  25:\t *\n  26:\t * The stub then passes the decoded arguments to the __se_sys_*() wrapper to\n  27:\t * perform sign-extension (omitted for zero-argument syscalls).  Finally the\n  28:\t * arguments are passed to the __do_sys_*() function which is the actual\n  29:\t * syscall.  These wrappers are marked as inline so the compiler can optimize\n  30:\t * the functions where appropriate.\n  31:\t *\n  32:\t * Example assembly (slightly re-ordered for better readability):\n  33:\t *\n  34:\t * \u003c__x64_sys_recv\u003e:\t\t\u003c-- syscall with 4 parameters\n  35:\t *\tcallq\t\u003c__fentry__\u003e\n  36:\t *\n  37:\t *\tmov\t0x70(%rdi),%rdi\t\u003c-- decode regs-\u003edi\n  38:\t *\tmov\t0x68(%rdi),%rsi\t\u003c-- decode regs-\u003esi\n  39:\t *\tmov\t0x60(%rdi),%rdx\t\u003c-- decode regs-\u003edx\n  40:\t *\tmov\t0x38(%rdi),%rcx\t\u003c-- decode regs-\u003er10\n  41:\t *\n  42:\t *\txor\t%r9d,%r9d\t\u003c-- clear %r9\n  43:\t *\txor\t%r8d,%r8d\t\u003c-- clear %r8\n  44:\t *\n  45:\t *\tcallq\t__sys_recvfrom\t\u003c-- do the actual work in __sys_recvfrom()\n  46:\t *\t\t\t\t    which takes 6 arguments\n  47:\t *\n  48:\t *\tcltq\t\t\t\u003c-- extend return value to 64-bit\n  49:\t *\tretq\t\t\t\u003c-- return\n  50:\t *\n  51:\t * This approach avoids leaking random user-provided register content down\n  52:\t * the call chain.\n  53:\t */\n  54:\t\n  55:\t/* Mapping of registers to parameters for syscalls on x86-64 and x32 */\n  56:\t#define SC_X86_64_REGS_TO_ARGS(x, ...)\t\t\t\t\t\\\n  57:\t\t__MAP(x,__SC_ARGS\t\t\t\t\t\t\\\n  58:\t\t\t,,regs-\u003edi,,regs-\u003esi,,regs-\u003edx\t\t\t\t\\\n  59:\t\t\t,,regs-\u003er10,,regs-\u003er8,,regs-\u003er9)\t\t\t\\\n  60:\t\n  61:\t\n  62:\t/* SYSCALL_PT_ARGS is Adapted from s390x */\n  63:\t#define SYSCALL_PT_ARG6(m, t1, t2, t3, t4, t5, t6)\t\t\t\\\n"
}

27/2 2026/11/24 16:38 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 88605
							output: 43
							thoughts: 21
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Diving into the Syscall Wrapper Header**

Alright, so we need to get down to brass tacks and see what `syscall_wrapper.h` is actually spitting out. I'm not just going to take the descriptions at face value, I want to see the generated function names themselves. What's the naming convention they've chosen? Are they using a prefix, suffix, or something completely custom? Are the arguments aligned as I'd expect for the target architecture and the kernel versions we are supporting? Are the return types consistent with the specifications? This file is where the rubber meets the road; it's where we can confirm (or debunk) our assumptions about the wrapper's behavior. We can verify if it's following the conventions of the project, and ensure the actual code generated is what we're expecting. Let's see what's what.



28/2 2026/11/24 16:39 tool read-file
0m Args:
{
  "File": "arch/x86/include/asm/syscall_wrapper.h",
  "FirstLine": 180,
  "LineCount": 50
}

Results:
{
  "Contents": " 180:\t\n 181:\t#else /* CONFIG_X86_X32_ABI */\n 182:\t#define __X32_COMPAT_SYS_STUB0(name)\n 183:\t#define __X32_COMPAT_SYS_STUBx(x, name, ...)\n 184:\t#define __X32_COMPAT_COND_SYSCALL(name)\n 185:\t#endif /* CONFIG_X86_X32_ABI */\n 186:\t\n 187:\t\n 188:\t#ifdef CONFIG_COMPAT\n 189:\t/*\n 190:\t * Compat means IA32_EMULATION and/or X86_X32. As they use a different\n 191:\t * mapping of registers to parameters, we need to generate stubs for each\n 192:\t * of them.\n 193:\t */\n 194:\t#define COMPAT_SYSCALL_DEFINE0(name)\t\t\t\t\t\\\n 195:\t\tstatic long\t\t\t\t\t\t\t\\\n 196:\t\t__do_compat_sys_##name(const struct pt_regs *__unused);\t\t\\\n 197:\t\t__IA32_COMPAT_SYS_STUB0(name)\t\t\t\t\t\\\n 198:\t\t__X32_COMPAT_SYS_STUB0(name)\t\t\t\t\t\\\n 199:\t\tstatic long\t\t\t\t\t\t\t\\\n 200:\t\t__do_compat_sys_##name(const struct pt_regs *__unused)\n 201:\t\n 202:\t#define COMPAT_SYSCALL_DEFINEx(x, name, ...)\t\t\t\t\t\\\n 203:\t\tstatic long __se_compat_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));\t\\\n 204:\t\tstatic inline long __do_compat_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\\\n 205:\t\t__IA32_COMPAT_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 206:\t\t__X32_COMPAT_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 207:\t\tstatic long __se_compat_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))\t\\\n 208:\t\t{\t\t\t\t\t\t\t\t\t\\\n 209:\t\t\treturn __do_compat_sys##name(__MAP(x,__SC_DELOUSE,__VA_ARGS__));\\\n 210:\t\t}\t\t\t\t\t\t\t\t\t\\\n 211:\t\tstatic inline long __do_compat_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\n 212:\t\n 213:\t/*\n 214:\t * As some compat syscalls may not be implemented, we need to expand\n 215:\t * COND_SYSCALL_COMPAT in kernel/sys_ni.c to cover this case as well.\n 216:\t */\n 217:\t#define COND_SYSCALL_COMPAT(name) \t\t\t\t\t\\\n 218:\t\t__IA32_COMPAT_COND_SYSCALL(name)\t\t\t\t\\\n 219:\t\t__X32_COMPAT_COND_SYSCALL(name)\n 220:\t\n 221:\t#endif /* CONFIG_COMPAT */\n 222:\t\n 223:\t#define __SYSCALL_DEFINEx(x, name, ...)\t\t\t\t\t\\\n 224:\t\tstatic long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__));\t\\\n 225:\t\tstatic inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\\\n 226:\t\t__X64_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 227:\t\t__IA32_SYS_STUBx(x, name, __VA_ARGS__)\t\t\t\t\\\n 228:\t\tstatic long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__))\t\\\n 229:\t\t{\t\t\t\t\t\t\t\t\\\n"
}

29/2 2026/11/24 16:39 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 89907
							output: 18
							thoughts: 1690
						

Thoughts:
**Root Namespace Implementation Review for Syzkaller Targeting**

Okay, let's break this down for Syzkaller. I'm looking at the `rootns` implementation, figuring out how to best target it.  First, let's clarify the x86-64 syscall entry point: `__X64_SYS_STUBx` generates `__x64_sys_##name`, right?  And we've got `__do_sys_##name` as either static inline or just static, with `__x64_sys_rootns` being the actual entry stub.  On x86-64, SYSCALL_DEFINEx makes `__x64_sys_rootns` the function called from the syscall table.  `__do_sys_rootns` is inline, which is a bit of a wrinkle, since it might or might not be inlined by the compiler.

So, the key question is, what symbols does Syzkaller typically focus on for syscalls? Right, let's consult the Syzkaller documentation in Section 4. It says to list functions that implement the logic or the entry points. So, we can target either `__x64_sys_rootns` or `sys_rootns`.  `sys_rootns` calls `create_rootns`, so it's a direct entry point, which is good.

I'm checking the functions within `kernel/rootns.c` and elsewhere: `create_rootns`, `rootns_ioctl`, and all the rest. Some of them, like `rootns_ioctl`, are clearly defined in a .c file and aren't static. Others like `create_rootns` are in a `.c` file, but could still be static. I need to figure out which are static and which aren't. Wait, static functions in .c files *can* be target symbols if they have addresses in the vmlinux! Let's re-read Section 4! If the functions are static *inline* in headers, they cannot be targeted directly. If the changes are primarily in static inline helpers, identify non-static, feature-specific caller functions in .c files that exercise them.

Ah, so the important point is "HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h)". If they are inline functions in headers, there are no distinct symbol addresses, and cannot be targeted directly, but static functions in .c files (unless static inline in headers) *do* exist in symbol tables if not fully inlined. `rootns_prepare_fork`, `rootns_finish_fork`, `copy_rootns`, `exit_rootns`, `mnt_ns_get_root`, `nsproxy_open_namespace`, etc. are explicitly non-static (defined in .c and declared in .h), and other functions like `rootns_ioctl`, `fsconfig_set_rootns`, `move_mount_mntns`, `rootns_wait`, `rootns_kill_members`, `create_rootns`, `proc_set_rootns`, and `mqueue_set_rootns` are in `.c` files.  And we have `__x64_sys_rootns` and `sys_rootns`. We can list both or either. Good. Listing both is common.

Now, let's assess if this is "WorthFuzzing". Yes, absolutely! This is a major new feature: root namespaces (`CONFIG_ROOTNS`).  It adds a new syscall `rootns` (`sys_rootns`), new ioctls like `ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`, poll support (EPOLLHUP), a new clone flag (`CLONE_INTO_ROOTNS`), `FSCONFIG_SET_ROOTNS`, `MOVE_MOUNT_T_MNTNS`, changes to `fsopen()`, `fsmount()`, `move_mount()`, new LSM hooks, and integration with various namespaces.  This code is *directly* reachable via standard syscalls like `rootns`, `clone3`, `fsopen`, etc., in QEMU.  So "WorthFuzzing: true."

Finally, we need `EnableConfigs`: What configs are needed to get this code built? `init/Kconfig` shows `ROOTNS` depends on `USER_NS`, `PID_NS`, `UTS_NS`, `IPC_NS`, `NET_NS`, and `CGROUPS`. It looks like `IS_ENABLED(CONFIG_TIME_NS)` is also used. And we need `CONFIG_NAMESPACES` as well as `CONFIG_ROOTNS`.  The selftests config confirms we need all the usual suspects: `


30/2 2026/11/24 16:40 tool grepper
0m Args:
{
  "Expression": "CONFIG_ROOTNS"
}

Results:
{
  "Output": "fs/fsopen.c=214=SYSCALL_DEFINE2(fsopen, const char __user *, _fs_name, unsigned int, flags)\n--\nfs/fsopen.c-222-\tpriv = may_mount();\nfs/fsopen.c:223:\tif (!priv \u0026\u0026 !IS_ENABLED(CONFIG_ROOTNS))\nfs/fsopen.c-224-\t\treturn -EPERM;\n--\nfs/namespace.c=4647=SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n--\nfs/namespace.c-4666-\nfs/namespace.c:4667:\tif (!(flags \u0026 FSMOUNT_NAMESPACE) \u0026\u0026 !IS_ENABLED(CONFIG_ROOTNS) \u0026\u0026\nfs/namespace.c-4668-\t    !priv)\n--\ninclude/linux/lsm_hook_defs.h=481=LSM_HOOK(int, 0, bdev_setintegrity, struct block_device *bdev,\n--\ninclude/linux/lsm_hook_defs.h-483-\ninclude/linux/lsm_hook_defs.h:484:#ifdef CONFIG_ROOTNS\ninclude/linux/lsm_hook_defs.h-485-LSM_HOOK(int, 0, rootns_alloc, struct rootns *rootns, unsigned int flags)\n--\ninclude/linux/lsm_hook_defs.h=488=LSM_HOOK(int, 0, rootns_kill, struct rootns *rootns, int sig)\ninclude/linux/lsm_hook_defs.h:489:#endif /* CONFIG_ROOTNS */\n--\ninclude/linux/lsm_hooks.h=104=struct lsm_blob_sizes {\n--\ninclude/linux/lsm_hooks.h-123-\tunsigned int lbs_bpf_token;\ninclude/linux/lsm_hooks.h:124:#ifdef CONFIG_ROOTNS\ninclude/linux/lsm_hooks.h-125-\tunsigned int lbs_rootns;\n--\ninclude/linux/pid_namespace.h=27=struct pid_namespace {\n--\ninclude/linux/pid_namespace.h-48-\tint reboot;\t/* group exit code if this pidns was rebooted */\ninclude/linux/pid_namespace.h:49:#ifdef CONFIG_ROOTNS\ninclude/linux/pid_namespace.h-50-\tstruct rootns *rootns;\n--\ninclude/linux/rootns.h=31=struct rootns {\n--\ninclude/linux/rootns.h-45-\ninclude/linux/rootns.h:46:#ifdef CONFIG_ROOTNS\ninclude/linux/rootns.h-47-struct rootns *get_rootns(struct rootns *c);\n--\ninclude/linux/rootns.h=85=static inline int rootns_finish_fork(struct kernel_clone_args *args,\n--\ninclude/linux/rootns.h-89-}\ninclude/linux/rootns.h:90:#endif /* CONFIG_ROOTNS */\ninclude/linux/rootns.h-91-\n--\ninclude/linux/sched/task.h=25=struct kernel_clone_args {\n--\ninclude/linux/sched/task.h-49-\tstruct css_set *cset;\ninclude/linux/sched/task.h:50:#ifdef CONFIG_ROOTNS\ninclude/linux/sched/task.h-51-\tstruct file *rootns_file;\n--\ninclude/linux/security.h=2468=static inline void security_initramfs_populated(void)\n--\ninclude/linux/security.h-2472-\ninclude/linux/security.h:2473:#ifdef CONFIG_ROOTNS\ninclude/linux/security.h-2474-#ifdef CONFIG_SECURITY\n--\ninclude/linux/security.h=2495=static inline int security_rootns_kill(struct rootns *rootns, int sig)\n--\ninclude/linux/security.h-2499-#endif /* CONFIG_SECURITY */\ninclude/linux/security.h:2500:#endif /* CONFIG_ROOTNS */\ninclude/linux/security.h-2501-\n--\nkernel/Makefile=153=obj-$(CONFIG_SCF_TORTURE_TEST) += scftorture.o\nkernel/Makefile-154-\nkernel/Makefile:155:obj-$(CONFIG_ROOTNS) += rootns.o\nkernel/Makefile-156-\n--\nkernel/bpf/bpf_lsm.c=407=BTF_ID(func, bpf_lsm_bdev_setintegrity)\nkernel/bpf/bpf_lsm.c:408:#ifdef CONFIG_ROOTNS\nkernel/bpf/bpf_lsm.c-409-BTF_ID(func, bpf_lsm_rootns_alloc)\n--\nkernel/bpf/bpf_lsm.c=411=BTF_ID(func, bpf_lsm_rootns_kill)\nkernel/bpf/bpf_lsm.c:412:#endif /* CONFIG_ROOTNS */\nkernel/bpf/bpf_lsm.c-413-BTF_SET_END(sleepable_lsm_hooks)\n--\nkernel/bpf/bpf_lsm.c=428=BTF_ID(func, bpf_lsm_bdev_free_security)\nkernel/bpf/bpf_lsm.c:429:#ifdef CONFIG_ROOTNS\nkernel/bpf/bpf_lsm.c-430-BTF_ID(func, bpf_lsm_rootns_alloc)\nkernel/bpf/bpf_lsm.c=431=BTF_ID(func, bpf_lsm_rootns_free)\nkernel/bpf/bpf_lsm.c:432:#endif /* CONFIG_ROOTNS */\nkernel/bpf/bpf_lsm.c-433-BTF_SET_END(untrusted_lsm_hooks)\n--\nkernel/fork.c=1631=enum copy_fs_flags_t {\n--\nkernel/fork.c-1635-\nkernel/fork.c:1636:#ifdef CONFIG_ROOTNS\nkernel/fork.c-1637-static inline struct rootns *clone_args_rootns(const struct kernel_clone_args *args)\n--\nsecurity/lsm_init.c=285=static void __init lsm_prepare(struct lsm_info *lsm)\n--\nsecurity/lsm_init.c-318-\tlsm_blob_size_update(\u0026blobs-\u003elbs_bpf_token, \u0026blob_sizes.lbs_bpf_token);\nsecurity/lsm_init.c:319:#ifdef CONFIG_ROOTNS\nsecurity/lsm_init.c-320-\tlsm_blob_size_update(\u0026blobs-\u003elbs_rootns, \u0026blob_sizes.lbs_rootns);\n--\nsecurity/lsm_init.c=410=int __init security_init(void)\n--\nsecurity/lsm_init.c-465-\t\tlsm_pr(\"blob(bpf_token) size %d\\n\", blob_sizes.lbs_bpf_token);\nsecurity/lsm_init.c:466:#ifdef CONFIG_ROOTNS\nsecurity/lsm_init.c-467-\t\tlsm_pr(\"blob(rootns) size %d\\n\", blob_sizes.lbs_rootns);\n--\nsecurity/security.c=394=static int lsm_ns_alloc(struct ns_common *ns)\n--\nsecurity/security.c-398-\nsecurity/security.c:399:#ifdef CONFIG_ROOTNS\nsecurity/security.c-400-/**\n--\nsecurity/security.c=408=static int lsm_rootns_alloc(struct rootns *rootns)\n--\nsecurity/security.c-412-}\nsecurity/security.c:413:#endif /* CONFIG_ROOTNS */\nsecurity/security.c-414-\n--\nsecurity/security.c=5811=void security_initramfs_populated(void)\n--\nsecurity/security.c-5815-\nsecurity/security.c:5816:#ifdef CONFIG_ROOTNS\nsecurity/security.c-5817-/**\n--\nsecurity/security.c=5879=int security_rootns_kill(struct rootns *rootns, int sig)\n--\nsecurity/security.c-5882-}\nsecurity/security.c:5883:#endif /* CONFIG_ROOTNS */\n--\ntools/testing/selftests/rootns/config=5=CONFIG_PROC_FS=y\ntools/testing/selftests/rootns/config:6:CONFIG_ROOTNS=y\ntools/testing/selftests/rootns/config-7-CONFIG_TIME_NS=y\n"
}

31/2 2026/11/24 16:41 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 94847
							output: 30
							thoughts: 62
						

Thoughts:
Here's my take on those thoughts:

**Verifying Namespace Dependencies for CONFIG_ROOTNS**

Right, so `CONFIG_ROOTNS` is pretty fundamental, and as I recall, it depends on a constellation of other namespaces: `USER_NS`, `PID_NS`, `UTS_NS`, `IPC_NS`, `NET_NS`, and crucially, the overarching `CGROUPS` as well. The implications are clear, without all these pieces the `CONFIG_ROOTNS` configuration simply won't function, or at the least, it is heavily restricted. I had better make sure that the `NAMESPACES` option, which likely ties all of these together, is properly defined. Let's dive into `init/Kconfig` and double-check how `NAMESPACES` is handled; I need to make sure my understanding is accurate, and that we have the proper basis for this and related functionality. We need to be solid on this for any future work in this area.



32/2 2026/11/24 16:42 tool grepper
0m Args:
{
  "Expression": "menuconfig NAMESPACES",
  "PathPrefixes": [
    "init/Kconfig"
  ]
}

Results:
{
  "Output": "init/Kconfig=1204=endif # CGROUPS\ninit/Kconfig-1205-\ninit/Kconfig:1206:menuconfig NAMESPACES\ninit/Kconfig-1207-\tbool \"Namespaces support\" if EXPERT\n"
}

33/2 2026/11/24 16:42 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 95224
							output: 27
							thoughts: 143
						

Thoughts:
**My Configuration Checklist**

Okay, let's nail down these kernel configurations. Right now, I need to be sure these are enabled: `ROOTNS`, `NAMESPACES`, `USER_NS`, `PID_NS`, `UTS_NS`, `IPC_NS`, `NET_NS`, `CGROUPS`, and `TIME_NS`. That's the baseline for namespace support, obviously.

Now, let's dig a bit deeper. I need to consider if there are other relevant configurations that are implicitly needed or might offer some added functionality. I know I should also be thinking about `SECURITY` for those LSM hooks, critical for sandboxing, obviously. I also have to verify that `PROC_FS` is enabled, as I'll need `proc_set_rootns`. And finally, I need to check `POSIX_MQUEUE`, as this is a key dependency for the mqueue functionality within `ipc/mqueue.c`. I should probably double-check the Kconfig dependencies for `ipc/mqueue.c` too, just to be thorough and be sure I'm not missing anything.



34/2 2026/11/24 16:44 tool grepper
0m Args:
{
  "Expression": "mqueue.o",
  "PathPrefixes": [
    "ipc/"
  ]
}

Results:
{
  "Output": "ipc/Makefile=8=obj-$(CONFIG_SYSVIPC_SYSCTL) += ipc_sysctl.o\nipc/Makefile:9:obj-$(CONFIG_POSIX_MQUEUE) += mqueue.o msgutil.o\nipc/Makefile-10-obj-$(CONFIG_IPC_NS) += namespace.o\n"
}

35/2 2026/11/24 16:44 llm patch-evaluator
2m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 95715
							output: 349
							thoughts: 1490
						

Thoughts:
**Root Namespace Fuzzing Verdict**

Okay, let's break this down. First, I'm confirming the obvious: `CONFIG_POSIX_MQUEUE` enables `mqueue.o`, `CONFIG_PROC_FS` enables `proc/root.o`, and `CONFIG_SECURITY` enables `security/security.o`. Makes sense. I'm also confirming the other related configs: `CONFIG_ROOTNS`, `CONFIG_NAMESPACES`, `CONFIG_USER_NS`, `CONFIG_PID_NS`, `CONFIG_UTS_NS`, `CONFIG_IPC_NS`, `CONFIG_NET_NS`, `CONFIG_CGROUPS`, and `CONFIG_TIME_NS` – all expected for this new root namespace feature.

Now, the real focus is identifying the right symbols for fuzzing. I need to be precise, non-ubiquitous, and directly related to the new functionality. I'm looking at: `sys_rootns` and its x86_64 stub `__x64_sys_rootns` for the syscall entry, `rootns_ioctl` for handling the new ioctls, specifically those related to rootns file descriptors, then `rootns_prepare_fork`, `rootns_finish_fork` for the clone integration and `copy_rootns`, `exit_rootns`, to track the thread group and process lifecycle changes. Also included are `fsconfig_set_rootns`, `move_mount_mntns` and helpers like `mnt_ns_get_root` and `nsproxy_open_namespace`, and the hooks `proc_set_rootns` and `mqueue_set_rootns` that are critical for FS integration.

I'm double-checking each one to ensure they are *not* widely used throughout the kernel. I can confirm these are strictly tied to the new rootns feature. No common functions, no page faults, no generic memory allocation. These are specific to this implementation. `create_rootns` is tempting to include, but I see it's static, and the entry point is `sys_rootns`, so I'm omitting it.

The reasoning here is critical. This patch introduces the `Root Namespace` feature (`CONFIG_ROOTNS`). That involves a new `rootns` syscall, the `CLONE_INTO_ROOTNS` clone3 flag, new ioctls (`ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`), the `FSCONFIG_SET_ROOTNS` fsconfig command, the `MOVE_MOUNT_T_MNTNS` move_mount flag, and integration with mount, pid, and user namespaces. These changes touch core VFS, fork/clone, namespaces, and security subsystems and are directly reachable from unprivileged/privileged userspace in virtualized environments. Fuzzing is essential to detect lifecycle race conditions, capability bypasses, memory leaks, and assertion failures.

I'm confident in the analysis. This is definitely worth fuzzing. I've got a comprehensive set of non-ubiquitous focus symbols. All requirements are met: `WorthFuzzing` is true, the `EnableConfigs` list is complete (and correct), the `FocusSymbols` list is precisely what I need, and the `Reasoning` is concise and accurate. Time to `set-results`.



36/2 2026/11/24 16:46 tool set-results
0m Args:
{
  "EnableConfigs": [
    "ROOTNS",
    "NAMESPACES",
    "USER_NS",
    "PID_NS",
    "UTS_NS",
    "IPC_NS",
    "NET_NS",
    "CGROUPS",
    "TIME_NS",
    "POSIX_MQUEUE",
    "PROC_FS",
    "SECURITY"
  ],
  "FocusSymbols": [
    "sys_rootns",
    "__x64_sys_rootns",
    "rootns_ioctl",
    "rootns_prepare_fork",
    "rootns_finish_fork",
    "copy_rootns",
    "exit_rootns",
    "fsconfig_set_rootns",
    "move_mount_mntns",
    "mnt_ns_get_root",
    "nsproxy_open_namespace",
    "proc_set_rootns",
    "mqueue_set_rootns"
  ],
  "Reasoning": "The patch introduces the root namespace (CONFIG_ROOTNS) subsystem, providing a new rootns() syscall, new ioctls (ROOTNS_GET_NSFD, ROOTNS_WAIT, ROOTNS_KILL), a new clone3 flag (CLONE_INTO_ROOTNS), fsconfig commands (FSCONFIG_SET_ROOTNS), and move_mount operations (MOVE_MOUNT_T_MNTNS). These modify core namespace, fork, VFS, and security subsystem logic that is directly reachable from userspace in standard virtualized environments. Fuzzing is highly warranted to test complex lifecycle transitions, concurrency, and security invariants.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "ROOTNS",
    "NAMESPACES",
    "USER_NS",
    "PID_NS",
    "UTS_NS",
    "IPC_NS",
    "NET_NS",
    "CGROUPS",
    "TIME_NS",
    "POSIX_MQUEUE",
    "PROC_FS",
    "SECURITY"
  ],
  "FocusSymbols": [
    "sys_rootns",
    "__x64_sys_rootns",
    "rootns_ioctl",
    "rootns_prepare_fork",
    "rootns_finish_fork",
    "copy_rootns",
    "exit_rootns",
    "fsconfig_set_rootns",
    "move_mount_mntns",
    "mnt_ns_get_root",
    "nsproxy_open_namespace",
    "proc_set_rootns",
    "mqueue_set_rootns"
  ],
  "Reasoning": "The patch introduces the root namespace (CONFIG_ROOTNS) subsystem, providing a new rootns() syscall, new ioctls (ROOTNS_GET_NSFD, ROOTNS_WAIT, ROOTNS_KILL), a new clone3 flag (CLONE_INTO_ROOTNS), fsconfig commands (FSCONFIG_SET_ROOTNS), and move_mount operations (MOVE_MOUNT_T_MNTNS). These modify core namespace, fork, VFS, and security subsystem logic that is directly reachable from userspace in standard virtualized environments. Fuzzing is highly warranted to test complex lifecycle transitions, concurrency, and security invariants.",
  "WorthFuzzing": true
}

37/1 2026/11/24 16:46 action If
8m Args:
{
  "WorthFuzzing": true
}

Results:
null

38/2 2026/11/24 16:46 agent kmsan-evaluator
8m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces the root namespace (`rootns`) facility, adding the `sys_rootns` syscall, `CLONE_INTO_ROOTNS` support in `clone3()`, `FSCONFIG_SET_ROOTNS` in `fsconfig()`, `MOVE_MOUNT_T_MNTNS` in `move_mount()`, and control ioctls (`ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`).\n\nKMSAN vs. KASAN analysis:\n- Potential bug risks in this patch: The patch modifies namespace reference counting (`mnt_ns`, `pid_ns`, `user_ns`, `nsproxy`), task credentials, mount hierarchy manipulation, and synchronization under locks (`tasklist_lock`, `rootns-\u003elock`, waitqueues). These represent risks of refcount leaks, use-after-free, double free, locking deadlocks, or capability bypasses—all of which are covered by standard KASAN, LOCKDEP, and standard kernel bug detectors.\n- Uninitialized memory / info-leak analysis (KMSAN):\n  1. Heap allocations: `struct rootns` is allocated with `kzalloc_obj()`, its LSM security blob is allocated with `kzalloc()` via `lsm_blob_alloc()`, and namespace structures use zeroed slab allocations (`kmem_cache_zalloc()`).\n  2. Stack variables: Stack paths (`struct path from_path`, `to_path`, `root`) use `= {}` zero-initialization with `__free()` cleanup helpers.\n  3. Kernel-to-user copies: The only user-facing structure copied to userspace is `struct rootns_wait_args` in `rootns_wait()`. It contains two 32-bit fields (`__u32 flags` at offset 0 and `__s32 status` at offset 4) totaling 8 bytes, with no internal or trailing padding bytes on either 32-bit or 64-bit architectures. It is read via `copy_from_user()`, `status` is overwritten, and written back via `copy_to_user()`, leaving zero chance of uninitialized data exposure.\n  4. User input handling: `copy_clone_args_from_user()` uses `copy_struct_from_user()`, which automatically zeroes trailing fields when older or smaller structs are passed.\n\nBecause no uninitialized memory risks or kernel info-leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted. Standard KASAN fuzzing is sufficient.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 5eee798c49d5a9e72c751aa7953598064d617c03
Author: syz-cluster <triage@syzkaller.com>
Date:   Tue Nov 24 16:16:22 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a85c..56d0ac4eb0879a 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 dbe46204099996..d8dc926ea28303 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 00000000000000..5326fd2eeb2123
--- /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
diff --git a/MAINTAINERS b/MAINTAINERS
index 8fd9991739547c..a24d0b16f42f42 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -24511,6 +24511,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
diff --git a/arch/alpha/kernel/syscalls/syscall.tbl b/arch/alpha/kernel/syscalls/syscall.tbl
index 52e3538cc7df41..ea790cceb67acf 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 55717ed32c27e6..531b2a2dce72d1 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 df2d1d82fb3ccf..8ef224c0dd42b6 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 ba7a4d8903d044..77239262dc26f5 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 76d7cbe2a133c4..df53332ce4a5b7 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 9ae88e4eac61ee..84db40158bf0b3 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 83dc93a0712f12..9e874a95850300 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 9c62429c9b7b4e..592c2225f4ce36 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 88adc4016cce01..93f8539bd1795d 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 cfbb70039ff007..7e12f74a27c1b4 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 1b45e68a217bb0..ab303fbb86f380 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 ace068dff0de03..e92778075bcb48 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 5b9fe0e8140f26..20d6c572d3f153 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 2c172ef48dfd33..98cb11b717e5ca 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 d5b6045b0090cc..674fa2b4b23878 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 d354bb231796c2..82b7344a099cb3 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/fs/devpts/inode.c b/fs/devpts/inode.c
index bd1e8eb26edb70..db5a5c7a07db01 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 3083d904df9bc6..9429844bf6bf9d 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 a50584df97bea7..cd004750b99c5b 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 70024870fefa2e..85b31af68a4d65 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 3f2fbac40f8ee5..d6815bf6ea9bb7 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 aecd05ac01705d..36ed48c3f64678 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);
 }
 
 /*
@@ -4614,16 +4653,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 +4700,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 +4750,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;
@@ -4725,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;
 
@@ -4736,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);
 }
 
 /*
@@ -4758,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)
@@ -4771,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;
@@ -4794,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);
 }
 
 /*
@@ -6582,6 +6743,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 +6773,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 +6796,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 +6817,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",
@@ -6708,6 +6880,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/fs/nsfs.c b/fs/nsfs.c
index 8179d69da03871..1de51cd475080e 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/fs/proc/root.c b/fs/proc/root.c
index 7fbbe92bf73a71..323296b030892d 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/cred.h b/include/linux/cred.h
index 49c26af3734908..9849366fd44b87 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/fs_context.h b/include/linux/fs_context.h
index d1727dffecc5e2..42648bec5cfa36 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/linux/lsm_hook_defs.h b/include/linux/lsm_hook_defs.h
index 87d9d06710cb26..2cb90ddedc14a2 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 13621e9e233e6b..217a59d428b158 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/mnt_namespace.h b/include/linux/mnt_namespace.h
index 0acd1089d149cf..98188d1f74280c 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/nsfs.h b/include/linux/nsfs.h
index 731b67fc2fecd1..bfba790ee1a7fb 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/nsproxy.h b/include/linux/nsproxy.h
index dc2447f5f09240..26b3b788cc909f 100644
--- a/include/linux/nsproxy.h
+++ b/include/linux/nsproxy.h
@@ -12,6 +12,8 @@ struct ipc_namespace;
 struct pid_namespace;
 struct cgroup_namespace;
 struct fs_struct;
+struct rootns;
+struct user_namespace;
 
 /*
  * A structure to contain pointers to all per-process
@@ -92,7 +94,12 @@ static inline struct cred *nsset_cred(struct nsset *set)
  *
  */
 
-int copy_namespaces(u64 flags, struct task_struct *tsk);
+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,
+		    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/pid_namespace.h b/include/linux/pid_namespace.h
index b20baaa7e62b75..6fd959f4d0d4da 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
new file mode 100644
index 00000000000000..795a79584231d9
--- /dev/null
+++ b/include/linux/rootns.h
@@ -0,0 +1,92 @@
+/* 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 kernel_clone_args;
+struct nsproxy;
+struct pid;
+struct pid_namespace;
+struct task_struct;
+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' */
+#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) */
+	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);
+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)
+{
+	return NULL;
+}
+
+static inline void put_rootns(struct rootns *c)
+{
+}
+
+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)
+{
+}
+
+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 90ed5bc3c7afee..e0c4e8ab02f154 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/security.h b/include/linux/security.h
index 40831fab54709a..995292f1c92eb9 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/include/linux/syscalls.h b/include/linux/syscalls.h
index 552d9710a0d574..7e630b612ef26c 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 58bd9728df5838..bdc185543893df 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/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 91232053775d8d..3600a903442e2b 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/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h
index 5b7e77a7c736ee..25902ed39d79c3 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/include/uapi/linux/mount.h b/include/uapi/linux/mount.h
index ac865edac5173e..7fa93de08ceb6c 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.
@@ -105,6 +106,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/include/uapi/linux/rootns.h b/include/uapi/linux/rootns.h
new file mode 100644
index 00000000000000..acd91d895c632d
--- /dev/null
+++ b/include/uapi/linux/rootns.h
@@ -0,0 +1,83 @@
+/* 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>
+#include <linux/types.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,
+};
+
+/**
+ * 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
+
+/**
+ * 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)
+
+/**
+ * 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)
+
+/**
+ * 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/include/uapi/linux/sched.h b/include/uapi/linux/sched.h
index 19ffeba894283e..405cfc954ae181 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/init/Kconfig b/init/Kconfig
index c8a7cfa60a6ea4..ed93dd11e6ac1f 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/ipc/mqueue.c b/ipc/mqueue.c
index 322c3dd98c4477..f94e9b566bd03b 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,
 };
 
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c52..7074d2664ce711 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/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c
index 468e63dbd922d0..bbcf1433fdc25a 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/cred.c b/kernel/cred.c
index d01df40a9a3861..48a8852dab4a06 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 5efceb8d58a78b..ac0497ff410cb9 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>
@@ -83,6 +84,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>
@@ -1615,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);
@@ -1631,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;
 
@@ -1648,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;
@@ -1670,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;
 }
 
@@ -2185,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;
 
@@ -2316,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);
@@ -2328,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);
@@ -2509,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;
@@ -2576,6 +2622,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, clone_args_rootns(args));
 		nr_threads++;
 	}
 	total_forks++;
@@ -2777,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
@@ -2798,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);
 
@@ -2955,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;
@@ -2985,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),
@@ -2996,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 &&
@@ -3036,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;
 
 	/*
@@ -3060,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 2dcf105e8ee2d4..78a1e1fb2cfd7f 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>
@@ -85,9 +86,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 +98,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;
 
@@ -166,12 +167,18 @@ static 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, 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);
 
@@ -231,7 +238,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 +296,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 +363,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);
 
diff --git a/kernel/pid_namespace.c b/kernel/pid_namespace.c
index 127a5fd23e7040..081c27aa85bd18 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
new file mode 100644
index 00000000000000..3733a249fecaa1
--- /dev/null
+++ b/kernel/rootns.c
@@ -0,0 +1,581 @@
+// 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/fs_struct.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 <linux/security.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;
+}
+
+static void free_rootns(struct rootns *c)
+{
+	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);
+}
+
+/*
+ * 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.
+ */
+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_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 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 ret;
+	int nr;
+
+	if (!pidns_is_ancestor(pid_ns, task_active_pid_ns(current)))
+		return -EXDEV;
+	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) {
+			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;
+
+	switch (cmd) {
+	case ROOTNS_GET_NSFD:
+		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;
+	}
+}
+
+#ifdef CONFIG_COMPAT
+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:
+	case ROOTNS_KILL:
+		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;
+}
+
+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);
+}
+
+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_free;
+	}
+	c->user_ns = user_ns;
+	ns_ref_active_get(user_ns);
+
+	if (!ns_capable(user_ns, CAP_SYS_ADMIN)) {
+		ret = -EPERM;
+		goto err_free;
+	}
+
+	ns = create_new_namespaces(clone_flags, current->nsproxy, user_ns,
+				   NULL);
+	if (IS_ERR(ns)) {
+		ret = PTR_ERR(ns);
+		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_free:
+	free_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;
+}
+
+/**
+ * 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 = security_rootns_clone(rootns);
+	if (ret)
+		return ret;
+
+	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/sys_ni.c b/kernel/sys_ni.c
index c8be0abaa40778..9fba98f15a2069 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);
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index cd748e1cbacef9..3bea8664719169 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;
diff --git a/scripts/syscall.tbl b/scripts/syscall.tbl
index 0ab5316051202e..b6d1b033f49ab2 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
diff --git a/security/lsm_init.c b/security/lsm_init.c
index 8d5ecea99c46b8..56b515b20812cb 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 4727b8347fc4e2..919d4bb6370139 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 */
diff --git a/tools/testing/selftests/Makefile b/tools/testing/selftests/Makefile
index 07c3719f8b04bf..7c44f93e57a475 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 00000000000000..62629d112e12f3
--- /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 00000000000000..21b1aecc003b86
--- /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 00000000000000..b690ed71a5211c
--- /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 00000000000000..7594b7a40c0cfe
--- /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 00000000000000..2cb23ca2ad290a
--- /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

39/3 2026/11/24 16:46 llm kmsan-evaluator
2m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 68613
							output: 34
							thoughts: 1640
						

Thoughts:
**KMSAN Fuzzing Evaluation for Root Namespace Patch Series**

Okay, let's break this down. The objective is to determine if this root namespace patch series warrants a dedicated KMSAN fuzzing session. I need to meticulously analyze the code for potential memory safety issues, particularly uninitialized reads and leaks, given the nature of the changes.

First, the patch introduces a new `rootns` feature, including a `sys_rootns` syscall, `CLONE_INTO_ROOTNS` for `clone3`, `fsconfig`, `move_mount` flags, and several new ioctls: `ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`. I've looked over the header files (`rootns.h`, `sched.h`) and relevant source files (`rootns.c`, `fsopen.c`, etc.) to get a handle on where the changes live.

The crucial part is scrutinizing anything that interacts with user-provided data, and any inter-process communication that might leave things dangling. Specifically, I'm focusing on the ioctl argument handling, `copy_to_user`, `put_user` and similar mechanisms.

The `rootns_wait` function immediately caught my eye. The `struct rootns_wait_args args;` on the stack is an area of concern. After the `copy_from_user` call to initialize `args`, I see an issue. If `rootns->state` isn't `ROOTNS_DEAD`, the function exits early, returning 0, *without* writing anything back to user space. It *only* writes back to the provided user space address if `rootns->state` *is* `ROOTNS_DEAD`. In this case, `args.status` is set based on `rootns->exit_code`, and I can see there is an int, read and then written.

Now, I'm also looking at `exit_rootns`. The potential for data races involving `tsk->signal->group_exit_code` or `leader->exit_code` is another angle. These values are integer-sized, but I need to be certain they are properly handled regarding concurrency and memory ordering.

Regarding other things to watch for, I've checked `create_rootns`. I see that the `kzalloc_obj` call initializes allocated memory, which is good. That said, I'll need to double-check this pattern for all allocations, making sure everything is zeroed, and also looking for where memory may be freed. I'm also looking at the `copy_clone_args_from_user` function. The code checks for `CLONE_INTO_ROOTNS` and its associated data but I need to examine its read behavior more closely.

Right now, I need to look at `kernel/fork.c`, around lines 2955-3000 to analyze how `args` is actually read from user space in `copy_clone_args_from_user`. I'll use the file browser to help. The critical question: Is there a potential information leak or uninitialized data read in any of the copy operations? This will dictate the intensity of the KMSAN fuzzing.



40/3 2026/11/24 16:49 tool read-file
0m Args:
{
  "File": "kernel/fork.c",
  "FirstLine": 2950,
  "LineCount": 70
}

Results:
{
  "Contents": "2950:\t\t/* can not support in nommu mode */\n2951:\t\treturn -EINVAL;\n2952:\t#endif\n2953:\t}\n2954:\t#endif\n2955:\t\n2956:\t#ifdef __ARCH_WANT_SYS_VFORK\n2957:\tSYSCALL_DEFINE0(vfork)\n2958:\t{\n2959:\t\tstruct kernel_clone_args args = {\n2960:\t\t\t.flags\t\t= CLONE_VFORK | CLONE_VM,\n2961:\t\t\t.exit_signal\t= SIGCHLD,\n2962:\t\t};\n2963:\t\n2964:\t\treturn kernel_clone(\u0026args);\n2965:\t}\n2966:\t#endif\n2967:\t\n2968:\t#ifdef __ARCH_WANT_SYS_CLONE\n2969:\t#ifdef CONFIG_CLONE_BACKWARDS\n2970:\tSYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,\n2971:\t\t\t int __user *, parent_tidptr,\n2972:\t\t\t unsigned long, tls,\n2973:\t\t\t int __user *, child_tidptr)\n2974:\t#elif defined(CONFIG_CLONE_BACKWARDS2)\n2975:\tSYSCALL_DEFINE5(clone, unsigned long, newsp, unsigned long, clone_flags,\n2976:\t\t\t int __user *, parent_tidptr,\n2977:\t\t\t int __user *, child_tidptr,\n2978:\t\t\t unsigned long, tls)\n2979:\t#elif defined(CONFIG_CLONE_BACKWARDS3)\n2980:\tSYSCALL_DEFINE6(clone, unsigned long, clone_flags, unsigned long, newsp,\n2981:\t\t\tint, stack_size,\n2982:\t\t\tint __user *, parent_tidptr,\n2983:\t\t\tint __user *, child_tidptr,\n2984:\t\t\tunsigned long, tls)\n2985:\t#else\n2986:\tSYSCALL_DEFINE5(clone, unsigned long, clone_flags, unsigned long, newsp,\n2987:\t\t\t int __user *, parent_tidptr,\n2988:\t\t\t int __user *, child_tidptr,\n2989:\t\t\t unsigned long, tls)\n2990:\t#endif\n2991:\t{\n2992:\t\tstruct kernel_clone_args args = {\n2993:\t\t\t.flags\t\t= (lower_32_bits(clone_flags) \u0026 ~CSIGNAL),\n2994:\t\t\t.pidfd\t\t= parent_tidptr,\n2995:\t\t\t.child_tid\t= child_tidptr,\n2996:\t\t\t.parent_tid\t= parent_tidptr,\n2997:\t\t\t.exit_signal\t= (lower_32_bits(clone_flags) \u0026 CSIGNAL),\n2998:\t\t\t.stack\t\t= newsp,\n2999:\t\t\t.tls\t\t= tls,\n3000:\t\t};\n3001:\t\n3002:\t\treturn kernel_clone(\u0026args);\n3003:\t}\n3004:\t#endif\n3005:\t\n3006:\tstatic noinline int copy_clone_args_from_user(struct kernel_clone_args *kargs,\n3007:\t\t\t\t\t\t      struct clone_args __user *uargs,\n3008:\t\t\t\t\t\t      size_t usize)\n3009:\t{\n3010:\t\tint err;\n3011:\t\tstruct clone_args args;\n3012:\t\tpid_t *kset_tid = kargs-\u003eset_tid;\n3013:\t\n3014:\t\tBUILD_BUG_ON(offsetofend(struct clone_args, tls) !=\n3015:\t\t\t     CLONE_ARGS_SIZE_VER0);\n3016:\t\tBUILD_BUG_ON(offsetofend(struct clone_args, set_tid_size) !=\n3017:\t\t\t     CLONE_ARGS_SIZE_VER1);\n3018:\t\tBUILD_BUG_ON(offsetofend(struct clone_args, cgroup) !=\n3019:\t\t\t     CLONE_ARGS_SIZE_VER2);\n"
}

41/3 2026/11/24 16:49 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 72068
							output: 34
							thoughts: 18
						

Thoughts:
Okay, here's my interpretation of that thought process, assuming I'm deep in the code:

**Diving into `copy_clone_args_from_user`**

Alright, I'm thinking, let's drill down into this `copy_clone_args_from_user` function. That seems to be where the core logic of this particular operation is. I need to understand exactly what's happening within this function and how it's dealing with the user's provided arguments. Are we talking about object cloning? Data copying? What are the specific structures and variables being used here? Are there any potentially tricky memory management considerations I need to be aware of? I need to know the exact interaction. This is where the magic (or the bugs!) are likely hiding. Time to dig in and understand this core piece of the functionality thoroughly.



42/3 2026/11/24 16:50 tool read-file
0m Args:
{
  "File": "kernel/fork.c",
  "FirstLine": 3020,
  "LineCount": 50
}

Results:
{
  "Contents": "3020:\t\tBUILD_BUG_ON(offsetofend(struct clone_args, rootns) !=\n3021:\t\t\t     CLONE_ARGS_SIZE_VER3);\n3022:\t\tBUILD_BUG_ON(sizeof(struct clone_args) != CLONE_ARGS_SIZE_VER3);\n3023:\t\n3024:\t\tif (unlikely(usize \u003e PAGE_SIZE))\n3025:\t\t\treturn -E2BIG;\n3026:\t\tif (unlikely(usize \u003c CLONE_ARGS_SIZE_VER0))\n3027:\t\t\treturn -EINVAL;\n3028:\t\n3029:\t\terr = copy_struct_from_user(\u0026args, sizeof(args), uargs, usize);\n3030:\t\tif (err)\n3031:\t\t\treturn err;\n3032:\t\n3033:\t\tif (unlikely(args.set_tid_size \u003e MAX_PID_NS_LEVEL))\n3034:\t\t\treturn -EINVAL;\n3035:\t\n3036:\t\tif (unlikely(!args.set_tid \u0026\u0026 args.set_tid_size \u003e 0))\n3037:\t\t\treturn -EINVAL;\n3038:\t\n3039:\t\tif (unlikely(args.set_tid \u0026\u0026 args.set_tid_size == 0))\n3040:\t\t\treturn -EINVAL;\n3041:\t\n3042:\t\t/*\n3043:\t\t * Verify that higher 32bits of exit_signal are unset\n3044:\t\t */\n3045:\t\tif (unlikely(args.exit_signal \u0026 ~((u64)CSIGNAL)))\n3046:\t\t\treturn -EINVAL;\n3047:\t\n3048:\t\tif ((args.flags \u0026 CLONE_INTO_CGROUP) \u0026\u0026\n3049:\t\t    (args.cgroup \u003e INT_MAX || usize \u003c CLONE_ARGS_SIZE_VER2))\n3050:\t\t\treturn -EINVAL;\n3051:\t\n3052:\t\tif ((args.flags \u0026 CLONE_INTO_ROOTNS) \u0026\u0026\n3053:\t\t    (args.rootns \u003e INT_MAX || usize \u003c CLONE_ARGS_SIZE_VER3))\n3054:\t\t\treturn -EINVAL;\n3055:\t\n3056:\t\t*kargs = (struct kernel_clone_args){\n3057:\t\t\t.flags\t\t= args.flags,\n3058:\t\t\t.pidfd\t\t= u64_to_user_ptr(args.pidfd),\n3059:\t\t\t.child_tid\t= u64_to_user_ptr(args.child_tid),\n3060:\t\t\t.parent_tid\t= u64_to_user_ptr(args.parent_tid),\n3061:\t\t\t.exit_signal\t= args.exit_signal,\n3062:\t\t\t.stack\t\t= args.stack,\n3063:\t\t\t.stack_size\t= args.stack_size,\n3064:\t\t\t.tls\t\t= args.tls,\n3065:\t\t\t.set_tid_size\t= args.set_tid_size,\n3066:\t\t\t.cgroup\t\t= args.cgroup,\n3067:\t\t\t.rootns_fd\t= args.rootns,\n3068:\t\t};\n3069:\t\n"
}

43/3 2026/11/24 16:50 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 73156
							output: 21
							thoughts: 260
						

Thoughts:
**Analyzing Root Namespace Security**

Okay, so `copy_struct_from_user` seems solid – it's taking care of trailing bytes, zeroing extra space when the user-provided size is smaller than the structure size, and importantly, it enforces that `usize` is at least `CLONE_ARGS_SIZE_VER3` when `CLONE_INTO_ROOTNS` is active. Good. Now, let's dive into the `rootns` code itself. I need to understand what `rootns` is doing with memory. I'm going to pinpoint every allocation, read, write to user space, and structure initialization within that context.

First stop: `kernel/rootns.c`. Looking at `create_rootns`, I see `c = kzalloc_obj(*c, GFP_KERNEL);`. Wait, `kzalloc_obj`... that implies it's using `kzalloc`. So all fields of the `struct rootns` are initialized to zero, which is important to know. Good. Now, let's check how the LSM blob allocation is handled. Specifically: `static int lsm_rootns_alloc(struct rootns *rootns)`... and that function calls `lsm_blob_alloc`. I should check how `lsm_blob_alloc` itself is defined. Let's do a quick grep for that function.



44/3 2026/11/24 16:50 tool grepper
0m Args:
{
  "Expression": "int lsm_blob_alloc"
}

Results:
{
  "Output": "security/security.c=187=static int lsm_backing_file_alloc(struct file *backing_file)\n--\nsecurity/security.c-212- */\nsecurity/security.c:213:static int lsm_blob_alloc(void **dest, size_t size, gfp_t gfp)\nsecurity/security.c-214-{\n"
}

45/3 2026/11/24 16:50 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 73832
							output: 33
							thoughts: 17
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into the Code: `security/security.c` Line 213**

Okay, time to dig into the heart of the matter. I need to understand what's happening at line 213 of `security/security.c`. Let's get right into it, I know how the codebase is structured, so there is no need for preliminaries. My goal is clear: understand the logic at that specific line. I am looking for a specific pattern or vulnerability. Let's see what we've got.



46/3 2026/11/24 16:50 tool read-file
0m Args:
{
  "File": "security/security.c",
  "FirstLine": 210,
  "LineCount": 15
}

Results:
{
  "Contents": " 210:\t *\n 211:\t * Returns 0, or -ENOMEM if memory can't be allocated.\n 212:\t */\n 213:\tstatic int lsm_blob_alloc(void **dest, size_t size, gfp_t gfp)\n 214:\t{\n 215:\t\tif (size == 0) {\n 216:\t\t\t*dest = NULL;\n 217:\t\t\treturn 0;\n 218:\t\t}\n 219:\t\n 220:\t\t*dest = kzalloc(size, gfp);\n 221:\t\tif (*dest == NULL)\n 222:\t\t\treturn -ENOMEM;\n 223:\t\treturn 0;\n 224:\t}\n"
}

47/3 2026/11/24 16:50 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 74220
							output: 35
							thoughts: 2104
						

Thoughts:
**Analyzing Root Namespace Wait and Context Initialization**

Okay, let's break this down. First, `lsm_blob_alloc` uses `kzalloc`, meaning the LSM blob is zero-initialized. Good. Now, focusing on `rootns_wait`, I see the structure `rootns_wait_args`, and I need to confirm there's no padding. The fields `flags` and `status` are both 4 bytes, so a total of 8 bytes with 4-byte alignment. Perfect; no padding. `copy_from_user` initializes all 8 bytes of the `args` struct, which is copied from user space. The `args.status` field is overwritten with `rootns->exit_code` before `copy_to_user`, and I need to trace where `rootns->exit_code` comes from.

In `create_rootns`, `kzalloc_obj` is used for `c`, so `c->exit_code` starts at zero. Then, when a process exits within that root namespace (`exit_rootns`), `c->exit_code` gets set to `status`. Finally, in `rootns_wait`, `args.status = rootns->exit_code;` confirms that the exit code is written back to user space. It all seems straightforward.

Next, I need to look at `rootns_compat_ioctl`. `compat_ptr(arg)` is passed to `rootns_ioctl`, which calls `rootns_wait`, so the 32-bit vs. 64-bit ABI is safe because the structure `struct rootns_wait_args` is identical. I've covered this before, but it's worth the double-check.

I also need to examine `fsconfig_set_rootns`. Okay, this function takes a `fs_context`, and based on the code flow of this function, I note that if `fc->ops->set_rootns` is available, this function will be invoked. I also notice `fs_context_for_unpriv_mount`, which is called for an unprivileged mount. It calls `alloc_fs_context`. This is where it gets interesting: When `init` is false in `alloc_fs_context`, the function returns without calling `init_fs_context`. This might cause an issue, and I need to confirm the state of `fc` in that scenario. I'll need to check the code inside `alloc_fs_context` to verify if anything important is left uninitialized if `init` is false, and I need to do so immediately to identify a potential vulnerability.



48/3 2026/11/24 16:51 tool read-file
0m Args:
{
  "File": "fs/fs_context.c",
  "FirstLine": 255,
  "LineCount": 60
}

Results:
{
  "Contents": " 255:\t * initialised with the supplied flags and, if a submount/automount from\n 256:\t * another superblock (referred to by @reference) is supplied, may have\n 257:\t * parameters such as namespaces copied across from that superblock.\n 258:\t */\n 259:\tstatic struct fs_context *alloc_fs_context(struct file_system_type *fs_type,\n 260:\t\t\t\t\t      struct dentry *reference,\n 261:\t\t\t\t\t      unsigned int sb_flags,\n 262:\t\t\t\t\t      unsigned int sb_flags_mask,\n 263:\t\t\t\t\t      enum fs_context_purpose purpose,\n 264:\t\t\t\t\t      bool init)\n 265:\t{\n 266:\t\tstruct fs_context *fc;\n 267:\t\tint ret = -ENOMEM;\n 268:\t\n 269:\t\tfc = kzalloc_obj(struct fs_context, GFP_KERNEL_ACCOUNT);\n 270:\t\tif (!fc)\n 271:\t\t\treturn ERR_PTR(-ENOMEM);\n 272:\t\n 273:\t\tfc-\u003epurpose\t= purpose;\n 274:\t\tfc-\u003esb_flags\t= sb_flags;\n 275:\t\tfc-\u003esb_flags_mask = sb_flags_mask;\n 276:\t\tfc-\u003efs_type\t= get_filesystem(fs_type);\n 277:\t\tfc-\u003ecred\t= get_current_cred();\n 278:\t\tfc-\u003enet_ns\t= get_net(current-\u003ensproxy-\u003enet_ns);\n 279:\t\tfc-\u003elog.prefix\t= fs_type-\u003ename;\n 280:\t\n 281:\t\tmutex_init(\u0026fc-\u003euapi_mutex);\n 282:\t\n 283:\t\tswitch (purpose) {\n 284:\t\tcase FS_CONTEXT_FOR_MOUNT:\n 285:\t\t\tfc-\u003euser_ns = get_user_ns(fc-\u003ecred-\u003euser_ns);\n 286:\t\t\tbreak;\n 287:\t\tcase FS_CONTEXT_FOR_SUBMOUNT:\n 288:\t\t\tfc-\u003euser_ns = get_user_ns(reference-\u003ed_sb-\u003es_user_ns);\n 289:\t\t\tbreak;\n 290:\t\tcase FS_CONTEXT_FOR_RECONFIGURE:\n 291:\t\t\tatomic_inc(\u0026reference-\u003ed_sb-\u003es_active);\n 292:\t\t\tfc-\u003euser_ns = get_user_ns(reference-\u003ed_sb-\u003es_user_ns);\n 293:\t\t\tfc-\u003eroot = dget(reference);\n 294:\t\t\tbreak;\n 295:\t\t}\n 296:\t\n 297:\t\tif (!init)\n 298:\t\t\treturn fc;\n 299:\t\n 300:\t\tret = fc-\u003efs_type-\u003einit_fs_context(fc);\n 301:\t\tif (ret \u003c 0)\n 302:\t\t\tgoto err_fc;\n 303:\t\tfc-\u003eneed_free = true;\n 304:\t\treturn fc;\n 305:\t\n 306:\terr_fc:\n 307:\t\tput_fs_context(fc);\n 308:\t\treturn ERR_PTR(ret);\n 309:\t}\n 310:\t\n 311:\tstruct fs_context *fs_context_for_mount(struct file_system_type *fs_type,\n 312:\t\t\t\t\t\tunsigned int sb_flags)\n 313:\t{\n 314:\t\treturn alloc_fs_context(fs_type, NULL, sb_flags, 0,\n"
}

49/3 2026/11/24 16:51 llm kmsan-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 77857
							output: 17
							thoughts: 1189
						

Thoughts:
**Analyzing Zero-Initialization Patterns in Filesystem Contexts**

Okay, let's break this down. My initial focus is on the zero-initialization patterns I'm seeing. I'm starting with `fc = kzalloc_obj(struct fs_context, GFP_KERNEL_ACCOUNT);`. The fact that `fc` is fully zero-allocated is immediately significant. This sets up a specific starting state.  If `init` is false, `fc->ops` is NULL, and `fc->need_free` is false.

I need to understand what happens to this `fc` in the `FS_CONTEXT_AWAITING_NS` phase. In `fsopen`, the phase is set to `FS_CONTEXT_CREATE_NS` if privileged, otherwise `FS_CONTEXT_AWAITING_NS`. The crucial part is in `vfs_fsconfig_locked`: If the phase is `FS_CONTEXT_AWAITING_NS` and the command isn't `FSCONFIG_SET_ROOTNS`, it returns `-EPERM`. This is a crucial security restriction, preventing unprivileged contexts from doing anything but setting the root namespace.

Now, what about the lifecycle of `fc` if it's closed before `FSCONFIG_SET_ROOTNS`? The `put_fs_context(fc)` function is the key. Since `need_free` is false (due to the zero initialization), it will not call `fc->ops->free`, meaning it then frees `fc->cred`, `fc->user_ns`, `fc->net_ns`, etc., all of which were initialized by `alloc_fs_context`.  That makes sense.

Next, I need to check something else. What about `move_mount_mntns`? I need to analyze `move_mount_mntns`. I see that the `from_path` and `to_path` are both zero-initialized with `{}`. This is another important zero-initialization pattern.

Now, let's switch to `mnt_ns_get_root`. I see that If `vfs_path_lookup` succeeds but the `root->mnt` points to the `mnt_ns`'s root, it does `*root = (struct path){};` and returns `-ENOENT`. This also represents a zero-initialization. In `copy_fs`, a similar pattern appears: a zero-initialized `root` struct, and the subsequent usage of `set_fs_root` and `set_fs_pwd`. This zero-initialization appears to represent an empty path.

Finally, in `kernel/fork.c`, I see `rootns_prepare_fork` also initializes a `struct path` and `struct file`. The zero-initialization of both structures seems to be a common pattern related to empty mounts.

Ah! There's one more thing: `fsmount`. I see the allocation of a mount namespace. I see the use of `seq_origin`. So, what is `seq_origin` in `struct mnt_namespace`? Time to check where `struct mnt_namespace` is defined, and look for it in the definition. Let's `grep` for `seq_origin` to better understand the code and how the zero-initialization pattern works.



50/3 2026/11/24 16:52 tool grepper
0m Args:
{
  "Expression": "seq_origin"
}

Results:
{
  "Output": "fs/mount.h=13=struct mnt_namespace {\n--\nfs/mount.h-23-\twait_queue_head_t\tpoll;\nfs/mount.h:24:\tu64\t\t\tseq_origin; /* Sequence number of origin mount namespace */\nfs/mount.h-25-\tu64 event;\n--\nfs/namespace.c=1003=static inline bool check_anonymous_mnt(struct mount *mnt)\n--\nfs/namespace.c-1009-\nfs/namespace.c:1010:\tseq = mnt-\u003emnt_ns-\u003eseq_origin;\nfs/namespace.c-1011-\treturn !seq || (seq == current-\u003ensproxy-\u003emnt_ns-\u003ens.ns_id);\n--\nfs/namespace.c=3165=static struct mnt_namespace *get_detached_copy(const struct path *path, unsigned int flags)\n--\nfs/namespace.c-3184-\t\tif (is_anon_ns(src_mnt_ns))\nfs/namespace.c:3185:\t\t\tns-\u003eseq_origin = src_mnt_ns-\u003eseq_origin;\nfs/namespace.c-3186-\t\telse\nfs/namespace.c:3187:\t\t\tns-\u003eseq_origin = src_mnt_ns-\u003ens.ns_id;\nfs/namespace.c-3188-\t}\n--\nfs/namespace.c=4647=SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,\n--\nfs/namespace.c-4757-\tif (!priv)\nfs/namespace.c:4758:\t\tns-\u003eseq_origin = fc-\u003erootns_mnt_id;\nfs/namespace.c-4759-\tmnt = real_mount(new_path.mnt);\n"
}

51/3 2026/11/24 16:52 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 80228
							output: 19
							thoughts: 1515
						

Thoughts:
**Deep Dive into Namespace Initialization and Lifecycle**

Okay, let's break this down. My initial focus is on `fc->rootns_mnt_id` and how it's being set. I see that `fsconfig_set_rootns` assigns it from `c->ns->mnt_ns->ns.ns_id`. The crucial piece here is that if `priv` is true, a `mnt_ns` is allocated with `alloc_mnt_ns`, which uses `kzalloc`. This looks standard, so let me pivot and confirm how the mnt_ns itself gets opened.

Let's look at `nsproxy_open_namespace` in `fs/nsfs.c`. It's a switch statement handling various namespace types, like `CLONE_NEWNS`, `CLONE_NEWCGROUP`, etc. The code checks for namespace references and returns the namespace common structure via `to_ns_common` within a conditional based on whether the reference count is greater than zero. Then, `open_namespace` is called. The function looks straightforward, so I’m confident that it allocates a file descriptor and returns it, as expected.

Now, let's trace this back to the cleanup and kill operations. Let me examine `rootns_kill_members`. This function intends to signal members of the root namespace. Interesting. It checks if the current process is a descendant of the root namespace's PID namespace. It ensures the root namespace is running. Then, it calls `security_rootns_kill`. Then, it iterates through tasks in the PID namespace's IDR using `idr_for_each_entry`, guarded by `tasklist_lock` within an RCU read lock. The `group_send_sig_info` function is called to send a signal to each task. It initializes these bools, `any_success`, `any_other`, and `any_perm` and `int other_err = 0` correctly. If any signal sends fail, then this returns a specific error.

The important point is the guarded access to the task list, which is good. The boolean flags track different failure scenarios. If there are any successes, that's fine. If there are other errors, or permission issues, then specific error codes are returned. This looks robust enough.

My next line of thought: how are these namespaces *created*? Let's check `create_new_namespaces` in `kernel/nsproxy.c`. A new `nsproxy` is allocated using `kmem_cache_alloc`, which is a good choice. Wait, let me make sure all fields in `new_nsp` get initialized. It appears that `create_new_namespaces` initializes every single namespace pointer in the `nsproxy` struct! `mnt_ns`, `uts_ns`, `ipc_ns`, `pid_ns_for_children`, `cgroup_ns`, `net_ns`, `time_ns_for_children`, and `time_ns` are all assigned. I need to double-check the `struct nsproxy` definition to be absolutely certain that all members are initialized. This looks sound from a memory management perspective, assuming all the allocation functions are doing their job correctly, and I'm confident about that.



52/3 2026/11/24 16:53 tool grepper
0m Args:
{
  "Expression": "struct nsproxy \\{"
}

Results:
{
  "Output": "include/linux/nsproxy.h=16=struct user_namespace;\n--\ninclude/linux/nsproxy.h-33- */\ninclude/linux/nsproxy.h:34:struct nsproxy {\ninclude/linux/nsproxy.h-35-\trefcount_t count;\n"
}

53/3 2026/11/24 16:53 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 82550
							output: 36
							thoughts: 20
						

Thoughts:
Here's a summary of my thinking process, assuming I'm an expert:

**Diving into the Kernel Namespace Plumbing**

Okay, let's get down to brass tacks. I'm going to pull up `include/linux/nsproxy.h` and focus on line 34. Right away, this tells me we're dealing with the core structures defining how namespaces are handled within the Linux kernel. The inclusion of this particular header file suggests we're probably looking at the `nsproxy` structure itself, or at least elements closely related to it. Line 34 is likely a declaration or definition integral to the framework used to isolate resources, and it's essential for how processes are able to see only their isolated view of these resources.



54/3 2026/11/24 16:53 tool read-file
0m Args:
{
  "File": "include/linux/nsproxy.h",
  "FirstLine": 34,
  "LineCount": 25
}

Results:
{
  "Contents": "  34:\tstruct nsproxy {\n  35:\t\trefcount_t count;\n  36:\t\tstruct uts_namespace *uts_ns;\n  37:\t\tstruct ipc_namespace *ipc_ns;\n  38:\t\tstruct mnt_namespace *mnt_ns;\n  39:\t\tstruct pid_namespace *pid_ns_for_children;\n  40:\t\tstruct net \t     *net_ns;\n  41:\t\tstruct time_namespace *time_ns;\n  42:\t\tstruct time_namespace *time_ns_for_children;\n  43:\t\tstruct cgroup_namespace *cgroup_ns;\n  44:\t};\n  45:\textern struct nsproxy init_nsproxy;\n  46:\t\n  47:\t/*\n  48:\t * A structure to encompass all bits needed to install\n  49:\t * a partial or complete new set of namespaces.\n  50:\t *\n  51:\t * If a new user namespace is requested cred will\n  52:\t * point to a modifiable set of credentials. If a pointer\n  53:\t * to a modifiable set is needed nsset_cred() must be\n  54:\t * used and tested.\n  55:\t */\n  56:\tstruct nsset {\n  57:\t\tunsigned flags;\n  58:\t\tstruct nsproxy *nsproxy;\n"
}

55/3 2026/11/24 16:53 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 83120
							output: 44
							thoughts: 927
						

Thoughts:
**Analyzing Namespace Creation in the Linux Kernel**

Okay, so I'm looking at how namespaces are created, specifically focusing on the interactions within the cloning process. I see that `refcount_set(&new_nsp->count, 1);` is already in `create_new_namespaces`, which handles initial setup, ensuring everything is initialized as expected. That's good.

Next, I'm examining `copy_namespaces`. It's pretty straightforward: reference counting and pointer assignment within the `copy_namespaces` function, which is exactly what I'd expect. `copy_namespaces` takes care of the namespace proxy (`nsproxy`) and how it's linked to the new task structure, `tsk`. It handles cases where a `rootns` is provided, setting the new task's namespace to the `rootns`.

Now, moving on to `copy_creds`. This is where it gets more interesting. I see a check using `ns_capable` to ensure the new process has the necessary capabilities (`CAP_SYS_ADMIN` and `CAP_SYS_CHROOT`) within the target root namespace (`rootns`). If not, it returns an error. The code then checks if the new credentials' user namespace is the same as the target `rootns`'s user namespace and, if not, installs the new user namespace's credentials using `install_user_ns_cred`. A bit later, there's a check comparing the old and new credentials' capabilities and user namespace. If they differ, the code accesses the `exec_state`.

Hold on, let me quickly pivot to `copy_exec_state`. The code in `kernel/fork.c` mentions the `CLONE_VM` flag, where siblings share the parent's `exec_state`. It looks like it increments the reference count on the shared `exec_state` and assigns it to the new task. Crucially, I notice that `CLONE_INTO_ROOTNS` cannot be combined with `CLONE_VM`. It looks like the check is done in `clone3_args_valid`, where a bitmask is used to see if an invalid flag is present. That makes sense, because I remember that flags have specific rules for usage.

Okay, let me shift gears slightly again, I need to understand how the `pid_namespace` is allocated, so I'll check its structure. And I'll dig into `create_pid_namespace` in `kernel/pid_namespace.c` to understand that bit.



56/3 2026/11/24 16:53 tool grepper
0m Args:
{
  "Expression": "kmem_cache_zalloc|kzalloc|create_pid_namespace",
  "PathPrefixes": [
    "kernel/pid_namespace.c"
  ]
}

Results:
{
  "Output": "kernel/pid_namespace.c=75=static void destroy_pid_namespace_work(struct work_struct *work);\nkernel/pid_namespace.c-76-\nkernel/pid_namespace.c:77:static struct pid_namespace *create_pid_namespace(struct user_namespace *user_ns,\nkernel/pid_namespace.c-78-\tstruct pid_namespace *parent_pid_ns)\n--\nkernel/pid_namespace.c-96-\terr = -ENOMEM;\nkernel/pid_namespace.c:97:\tns = kmem_cache_zalloc(pid_ns_cachep, GFP_KERNEL);\nkernel/pid_namespace.c-98-\tif (ns == NULL)\n--\nkernel/pid_namespace.c=176=struct pid_namespace *copy_pid_ns(u64 flags,\n--\nkernel/pid_namespace.c-182-\t\treturn ERR_PTR(-EINVAL);\nkernel/pid_namespace.c:183:\treturn create_pid_namespace(user_ns, old_ns);\nkernel/pid_namespace.c-184-}\n"
}

57/3 2026/11/24 16:53 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 84908
							output: 580
							thoughts: 4563
						

Thoughts:
**KMSAN Assessment: Root Namespace (rootns) Implementation**

Alright, let's break this down. My goal is to determine if this root namespace patch series necessitates a Kernel Memory Sanitizer (KMSAN) test run, or if standard kernel sanitizers will suffice. The core concern here is uninitialized memory reads, or kernel information leaks.

First, I examine the memory allocation patterns within this patch. I see `kmem_cache_zalloc`, `kzalloc_obj`, and similar zero-initializing functions being used for `struct rootns`, `struct fs_context`, LSM blobs, and various other data structures. Good. This is the first important check, it removes the immediate risk of uninitialized memory at allocation. All stack variables are also properly initialized.

Next, I check any kernel structures that are copied to userspace. The only candidate I see is `struct rootns_wait_args`, used in the `ROOTNS_WAIT` ioctl. I drill down into this struct to make sure it's fully initialized before returning data to userspace, and no padding exists where uninitialized memory could be leaked. The code does initialize the fields, and there are no padding bytes between the members, ensuring that only initialized memory is copied out.

Then I carefully review the conditional statements and branching logic added. I'm looking for situations where control flow might depend on potentially uninitialized variables. However, all variables used in those checks are either explicitly initialized, or they have default zero values from their allocation.

Finally, I scrutinize the code for any potential buffer overflows or length-related issues that might allow access to uninitialized bytes of existing buffers. The code in the patch properly employs checks like `copy_struct_from_user` or `copy_from_user`, so there is no risk of reading uninitialized bytes.

Based on this assessment, I conclude that this patch series does *not* introduce a risk of uninitialized memory reads or information leaks. The standard KASAN and LOCKDEP toolchain is sufficient. The risks this patch *does* involve include reference counting issues, locking issues, privilege escalations, or mount logic problems, but these are issues caught by other standard fuzzing techniques. KMSAN would not provide any additional value here.

Therefore, setting `NeedsKMSAN=false` is appropriate.



58/3 2026/11/24 16:54 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces the root namespace (`rootns`) facility, adding the `sys_rootns` syscall, `CLONE_INTO_ROOTNS` support in `clone3()`, `FSCONFIG_SET_ROOTNS` in `fsconfig()`, `MOVE_MOUNT_T_MNTNS` in `move_mount()`, and control ioctls (`ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`).\n\nKMSAN vs. KASAN analysis:\n- Potential bug risks in this patch: The patch modifies namespace reference counting (`mnt_ns`, `pid_ns`, `user_ns`, `nsproxy`), task credentials, mount hierarchy manipulation, and synchronization under locks (`tasklist_lock`, `rootns-\u003elock`, waitqueues). These represent risks of refcount leaks, use-after-free, double free, locking deadlocks, or capability bypasses—all of which are covered by standard KASAN, LOCKDEP, and standard kernel bug detectors.\n- Uninitialized memory / info-leak analysis (KMSAN):\n  1. Heap allocations: `struct rootns` is allocated with `kzalloc_obj()`, its LSM security blob is allocated with `kzalloc()` via `lsm_blob_alloc()`, and namespace structures use zeroed slab allocations (`kmem_cache_zalloc()`).\n  2. Stack variables: Stack paths (`struct path from_path`, `to_path`, `root`) use `= {}` zero-initialization with `__free()` cleanup helpers.\n  3. Kernel-to-user copies: The only user-facing structure copied to userspace is `struct rootns_wait_args` in `rootns_wait()`. It contains two 32-bit fields (`__u32 flags` at offset 0 and `__s32 status` at offset 4) totaling 8 bytes, with no internal or trailing padding bytes on either 32-bit or 64-bit architectures. It is read via `copy_from_user()`, `status` is overwritten, and written back via `copy_to_user()`, leaving zero chance of uninitialized data exposure.\n  4. User input handling: `copy_clone_args_from_user()` uses `copy_struct_from_user()`, which automatically zeroes trailing fields when older or smaller structs are passed.\n\nBecause no uninitialized memory risks or kernel info-leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted. Standard KASAN fuzzing is sufficient.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces the root namespace (`rootns`) facility, adding the `sys_rootns` syscall, `CLONE_INTO_ROOTNS` support in `clone3()`, `FSCONFIG_SET_ROOTNS` in `fsconfig()`, `MOVE_MOUNT_T_MNTNS` in `move_mount()`, and control ioctls (`ROOTNS_GET_NSFD`, `ROOTNS_WAIT`, `ROOTNS_KILL`).\n\nKMSAN vs. KASAN analysis:\n- Potential bug risks in this patch: The patch modifies namespace reference counting (`mnt_ns`, `pid_ns`, `user_ns`, `nsproxy`), task credentials, mount hierarchy manipulation, and synchronization under locks (`tasklist_lock`, `rootns-\u003elock`, waitqueues). These represent risks of refcount leaks, use-after-free, double free, locking deadlocks, or capability bypasses—all of which are covered by standard KASAN, LOCKDEP, and standard kernel bug detectors.\n- Uninitialized memory / info-leak analysis (KMSAN):\n  1. Heap allocations: `struct rootns` is allocated with `kzalloc_obj()`, its LSM security blob is allocated with `kzalloc()` via `lsm_blob_alloc()`, and namespace structures use zeroed slab allocations (`kmem_cache_zalloc()`).\n  2. Stack variables: Stack paths (`struct path from_path`, `to_path`, `root`) use `= {}` zero-initialization with `__free()` cleanup helpers.\n  3. Kernel-to-user copies: The only user-facing structure copied to userspace is `struct rootns_wait_args` in `rootns_wait()`. It contains two 32-bit fields (`__u32 flags` at offset 0 and `__s32 status` at offset 4) totaling 8 bytes, with no internal or trailing padding bytes on either 32-bit or 64-bit architectures. It is read via `copy_from_user()`, `status` is overwritten, and written back via `copy_to_user()`, leaving zero chance of uninitialized data exposure.\n  4. User input handling: `copy_clone_args_from_user()` uses `copy_struct_from_user()`, which automatically zeroes trailing fields when older or smaller structs are passed.\n\nBecause no uninitialized memory risks or kernel info-leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted. Standard KASAN fuzzing is sufficient.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)