]> git.ipfire.org Git - thirdparty/linux.git/log
thirdparty/linux.git
3 weeks agons: drop custom reference count initialization for initial namespaces
Christian Brauner [Mon, 10 Nov 2025 15:08:28 +0000 (16:08 +0100)] 
ns: drop custom reference count initialization for initial namespaces

Initial namespaces don't modify their reference count anymore.
They remain fixed at one so drop the custom refcount initializations.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-16-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agopid: rely on common reference count behavior
Christian Brauner [Mon, 10 Nov 2025 15:08:27 +0000 (16:08 +0100)] 
pid: rely on common reference count behavior

Now that we changed the generic reference counting mechanism for all
namespaces to never manipulate reference counts of initial namespaces we
can drop the special handling for pid namespaces.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-15-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: add asserts for initial namespace active reference counts
Christian Brauner [Mon, 10 Nov 2025 15:08:26 +0000 (16:08 +0100)] 
ns: add asserts for initial namespace active reference counts

They always remain fixed at one. Notice when that assumptions is broken.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-14-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: add asserts for initial namespace reference counts
Christian Brauner [Mon, 10 Nov 2025 15:08:25 +0000 (16:08 +0100)] 
ns: add asserts for initial namespace reference counts

They always remain fixed at one. Notice when that assumptions is broken.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-13-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: make all reference counts on initial namespace a nop
Christian Brauner [Mon, 10 Nov 2025 15:08:24 +0000 (16:08 +0100)] 
ns: make all reference counts on initial namespace a nop

They are always active so no need to needlessly cacheline ping-pong.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-12-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoipc: enable is_ns_init_id() assertions
Christian Brauner [Mon, 10 Nov 2025 15:08:23 +0000 (16:08 +0100)] 
ipc: enable is_ns_init_id() assertions

The ipc namespace may call put_ipc_ns() and get_ipc_ns() before it is
added to the namespace tree. Assign the id early like we do for a some
other namespaces.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-11-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agofs: use boolean to indicate anonymous mount namespace
Christian Brauner [Mon, 10 Nov 2025 15:08:22 +0000 (16:08 +0100)] 
fs: use boolean to indicate anonymous mount namespace

Stop playing games with the namespace id and use a boolean instead:

* This will remove the special-casing we need to do everywhere for mount
  namespaces.

* It will allow us to use asserts on the namespace id for initial
  namespaces everywhere.

* It will allow us to put anonymous mount namespaces on the namespaces
  trees in the future and thus make them available to statmount() and
  listmount().

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-10-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: rename is_initial_namespace()
Christian Brauner [Mon, 10 Nov 2025 15:08:21 +0000 (16:08 +0100)] 
ns: rename is_initial_namespace()

Rename is_initial_namespace() to ns_init_inum() and make it symmetrical
with the ns id variant.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-9-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: make is_initial_namespace() argument const
Christian Brauner [Mon, 10 Nov 2025 15:08:20 +0000 (16:08 +0100)] 
ns: make is_initial_namespace() argument const

We don't modify the data structure at all so pass it as const.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-8-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: use guards for ns_tree_lock
Christian Brauner [Mon, 10 Nov 2025 15:08:19 +0000 (16:08 +0100)] 
nstree: use guards for ns_tree_lock

Make use of the guard infrastructure for ns_tree_lock.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-7-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: simplify owner list iteration
Christian Brauner [Mon, 10 Nov 2025 15:08:18 +0000 (16:08 +0100)] 
nstree: simplify owner list iteration

Make use of list_for_each_entry_from_rcu().

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-6-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: switch to new structures
Christian Brauner [Mon, 10 Nov 2025 15:08:17 +0000 (16:08 +0100)] 
nstree: switch to new structures

Switch the nstree management to the new combined structures.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-5-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: add helper to operate on struct ns_tree_{node,root}
Christian Brauner [Mon, 10 Nov 2025 15:08:16 +0000 (16:08 +0100)] 
nstree: add helper to operate on struct ns_tree_{node,root}

Add helpers that work on the combined rbtree and rculist combined.
This will make the code a lot more managable and legible.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-4-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: move nstree types into separate header
Christian Brauner [Mon, 10 Nov 2025 15:08:15 +0000 (16:08 +0100)] 
nstree: move nstree types into separate header

Introduce two new fundamental data structures for namespace tree
management in a separate header file.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-3-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agonstree: decouple from ns_common header
Christian Brauner [Mon, 10 Nov 2025 15:08:14 +0000 (16:08 +0100)] 
nstree: decouple from ns_common header

Foward declare struct ns_common and remove the include of ns_common.h.
We want ns_common.h to possibly include nstree structures but not the
other way around.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-2-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: move namespace types into separate header
Christian Brauner [Mon, 10 Nov 2025 15:08:13 +0000 (16:08 +0100)] 
ns: move namespace types into separate header

Add a dedicated header for namespace types.

Link: https://patch.msgid.link/20251110-work-namespace-nstree-fixes-v1-1-e8a9264e0fb9@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoMerge branch 'kbuild-6.19.fms.extension'
Christian Brauner [Tue, 11 Nov 2025 08:59:08 +0000 (09:59 +0100)] 
Merge branch 'kbuild-6.19.fms.extension'

Bring in the shared branch with the kbuild tree to enable
'-fms-extensions' for 6.19. Further namespace cleanup work
requires this extension.

Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoMerge patch series "ns: fixes for namespace iteration and active reference counting"
Christian Brauner [Mon, 10 Nov 2025 09:21:00 +0000 (10:21 +0100)] 
Merge patch series "ns: fixes for namespace iteration and active reference counting"

Christian Brauner <brauner@kernel.org> says:

* Make sure to initialize the active reference count for the initial
  network namespace and prevent __ns_common_init() from returning too
  early.

* Make sure that passive reference counts are dropped outside of rcu
  read locks as some namespaces such as the mount namespace do in fact
  sleep when putting the last reference.

* The setns() system call supports:

  (1) namespace file descriptors (nsfd)
  (2) process file descriptors (pidfd)

  When using nsfds the namespaces will remain active because they are
  pinned by the vfs. However, when pidfds are used things are more
  complicated.

  When the target task exits and passes through exit_nsproxy_namespaces()
  or is reaped and thus also passes through exit_cred_namespaces() after
  the setns()'ing task has called prepare_nsset() but before the active
  reference count of the set of namespaces it wants to setns() to might
  have been dropped already:

    P1                                                              P2

    pid_p1 = clone(CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS)
                                                                    pidfd = pidfd_open(pid_p1)
                                                                    setns(pidfd, CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS)
                                                                    prepare_nsset()

    exit(0)
    // ns->__ns_active_ref        == 1
    // parent_ns->__ns_active_ref == 1
    -> exit_nsproxy_namespaces()
    -> exit_cred_namespaces()

    // ns_active_ref_put() will also put
    // the reference on the owner of the
    // namespace. If the only reason the
    // owning namespace was alive was
    // because it was a parent of @ns
    // it's active reference count now goes
    // to zero... --------------------------------
    //                                           |
    // ns->__ns_active_ref        == 0           |
    // parent_ns->__ns_active_ref == 0           |
                                                 |                  commit_nsset()
                                                 -----------------> // If setns()
                                                                    // now manages to install the namespaces
                                                                    // it will call ns_active_ref_get()
                                                                    // on them thus bumping the active reference
                                                                    // count from zero again but without also
                                                                    // taking the required reference on the owner.
                                                                    // Thus we get:
                                                                    //
                                                                    // ns->__ns_active_ref        == 1
                                                                    // parent_ns->__ns_active_ref == 0

    When later someone does ns_active_ref_put() on @ns it will underflow
    parent_ns->__ns_active_ref leading to a splat from our asserts
    thinking there are still active references when in fact the counter
    just underflowed.

  So resurrect the ownership chain if necessary as well. If the caller
  succeeded to grab passive references to the set of namespaces the
  setns() should simply succeed even if the target task exists or gets
  reaped in the meantime.

  The race is rare and can only be triggered when using pidfs to setns()
  to namespaces. Also note that active reference on initial namespaces are
  nops.

  Since we now always handle parent references directly we can drop
  ns_ref_active_get_owner() when adding a namespace to a namespace tree.
  This is now all handled uniformly in the places where the new namespaces
  actually become active.

* patches from https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-0-ae8a4ad5a3b3@kernel.org:
  selftests/namespaces: test for efault
  selftests/namespaces: add active reference count regression test
  ns: add asserts for active refcount underflow
  ns: handle setns(pidfd, ...) cleanly
  ns: return EFAULT on put_user() error
  ns: make sure reference are dropped outside of rcu lock
  ns: don't increment or decrement initial namespaces
  ns: don't skip active reference count initialization

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-0-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoselftests/namespaces: test for efault
Christian Brauner [Sun, 9 Nov 2025 21:11:29 +0000 (22:11 +0100)] 
selftests/namespaces: test for efault

Ensure that put_user() can fail and that namespace cleanup works
correctly.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-8-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoMerge patch "kbuild: Add '-fms-extensions' to areas with dedicated CFLAGS"
Christian Brauner [Mon, 10 Nov 2025 09:38:07 +0000 (10:38 +0100)] 
Merge patch "kbuild: Add '-fms-extensions' to areas with dedicated CFLAGS"

Nathan Chancellor <nathan@kernel.org> says:

Shared branch between Kbuild and other trees for enabling
'-fms-extensions' for 6.19.

* tag 'kbuild-ms-extensions-6.19' of ssh://gitolite.kernel.org/pub/scm/linux/kernel/git/kbuild/linux:
  kbuild: Add '-fms-extensions' to areas with dedicated CFLAGS
  Kbuild: enable -fms-extensions
  jfs: Rename _inline to avoid conflict with clang's '-fms-extensions'

Link: https://patch.msgid.link/20251101-kbuild-ms-extensions-dedicated-cflags-v1-1-38004aba524b@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agoselftests/namespaces: add active reference count regression test
Christian Brauner [Sun, 9 Nov 2025 21:11:28 +0000 (22:11 +0100)] 
selftests/namespaces: add active reference count regression test

Add a regression test for setns() with pidfd.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-7-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: add asserts for active refcount underflow
Christian Brauner [Sun, 9 Nov 2025 21:11:27 +0000 (22:11 +0100)] 
ns: add asserts for active refcount underflow

Add a few more assert to detect active reference count underflows.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-6-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: handle setns(pidfd, ...) cleanly
Christian Brauner [Sun, 9 Nov 2025 21:11:26 +0000 (22:11 +0100)] 
ns: handle setns(pidfd, ...) cleanly

The setns() system call supports:

(1) namespace file descriptors (nsfd)
(2) process file descriptors (pidfd)

When using nsfds the namespaces will remain active because they are
pinned by the vfs. However, when pidfds are used things are more
complicated.

When the target task exits and passes through exit_nsproxy_namespaces()
or is reaped and thus also passes through exit_cred_namespaces() after
the setns()'ing task has called prepare_nsset() but before the active
reference count of the set of namespaces it wants to setns() to might
have been dropped already:

  P1                                                              P2

  pid_p1 = clone(CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS)
                                                                  pidfd = pidfd_open(pid_p1)
                                                                  setns(pidfd, CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS)
                                                                  prepare_nsset()

  exit(0)
  // ns->__ns_active_ref        == 1
  // parent_ns->__ns_active_ref == 1
  -> exit_nsproxy_namespaces()
  -> exit_cred_namespaces()

  // ns_active_ref_put() will also put
  // the reference on the owner of the
  // namespace. If the only reason the
  // owning namespace was alive was
  // because it was a parent of @ns
  // it's active reference count now goes
  // to zero... --------------------------------
  //                                           |
  // ns->__ns_active_ref        == 0           |
  // parent_ns->__ns_active_ref == 0           |
                                               |                  commit_nsset()
                                               -----------------> // If setns()
                                                                  // now manages to install the namespaces
                                                                  // it will call ns_active_ref_get()
                                                                  // on them thus bumping the active reference
                                                                  // count from zero again but without also
                                                                  // taking the required reference on the owner.
                                                                  // Thus we get:
                                                                  //
                                                                  // ns->__ns_active_ref        == 1
                                                                  // parent_ns->__ns_active_ref == 0

  When later someone does ns_active_ref_put() on @ns it will underflow
  parent_ns->__ns_active_ref leading to a splat from our asserts
  thinking there are still active references when in fact the counter
  just underflowed.

So resurrect the ownership chain if necessary as well. If the caller
succeeded to grab passive references to the set of namespaces the
setns() should simply succeed even if the target task exists or gets
reaped in the meantime and thus has dropped all active references to its
namespaces.

The race is rare and can only be triggered when using pidfs to setns()
to namespaces. Also note that active reference on initial namespaces are
nops.

Since we now always handle parent references directly we can drop
ns_ref_active_get_owner() when adding a namespace to a namespace tree.
This is now all handled uniformly in the places where the new namespaces
actually become active.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-5-ae8a4ad5a3b3@kernel.org
Fixes: 3c9820d5c64a ("ns: add active reference count")
Reported-by: syzbot+1957b26299cf3ff7890c@syzkaller.appspotmail.com
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: return EFAULT on put_user() error
Christian Brauner [Sun, 9 Nov 2025 21:11:25 +0000 (22:11 +0100)] 
ns: return EFAULT on put_user() error

Don't return EINVAL, return EFAULT just like we do in other system
calls.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-4-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: make sure reference are dropped outside of rcu lock
Christian Brauner [Sun, 9 Nov 2025 21:11:24 +0000 (22:11 +0100)] 
ns: make sure reference are dropped outside of rcu lock

The mount namespace may in fact sleep when putting the last passive
reference so we need to drop the namespace reference outside of the rcu
read lock. Do this by delaying the put until the next iteration where
we've already moved on to the next namespace and legitimized it. Once we
drop the rcu read lock to call put_user() we will also drop the
reference to the previous namespace in the tree.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-3-ae8a4ad5a3b3@kernel.org
Fixes: 76b6f5dfb3fd ("nstree: add listns()")
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: don't increment or decrement initial namespaces
Christian Brauner [Sun, 9 Nov 2025 21:11:23 +0000 (22:11 +0100)] 
ns: don't increment or decrement initial namespaces

There's no need to bump the active reference counts of initial
namespaces as they're always active and can simply remain at 1.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-2-ae8a4ad5a3b3@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
3 weeks agons: don't skip active reference count initialization
Christian Brauner [Sun, 9 Nov 2025 21:11:22 +0000 (22:11 +0100)] 
ns: don't skip active reference count initialization

Don't skip active reference count initialization for initial namespaces.
Doing this will break network namespace active reference counting.

Link: https://patch.msgid.link/20251109-namespace-6-19-fixes-v1-1-ae8a4ad5a3b3@kernel.org
Fixes: 3a18f809184b ("ns: add active reference count")
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoMerge patch series "nstree: listns()"
Christian Brauner [Thu, 30 Oct 2025 12:04:20 +0000 (13:04 +0100)] 
Merge patch series "nstree: listns()"

Christian Brauner <brauner@kernel.org> says:

As announced a while ago this is the next step building on the nstree
work from prior cycles. There's a bunch of fixes and semantic cleanups
in here and a ton of tests.

Currently listns() is relying on active namespace reference counts which
are introduced alongside this series.

While a namespace is on the namespace trees with a valid reference count
it is possible to reopen it through a namespace file handle. This is all
fine but has some issues that should be addressed.

On current kernels a namespace is visible to userspace in the
following cases:

(1) The namespace is in use by a task.
(2) The namespace is persisted through a VFS object (namespace file
    descriptor or bind-mount).
    Note that (2) only cares about direct persistence of the namespace
    itself not indirectly via e.g., file->f_cred file references or
    similar.
(3) The namespace is a hierarchical namespace type and is the parent of
    a single or multiple child namespaces.

Case (3) is interesting because it is possible that a parent namespace
might not fulfill any of (1) or (2), i.e., is invisible to userspace but
it may still be resurrected through the NS_GET_PARENT ioctl().

Currently namespace file handles allow much broader access to namespaces
than what is currently possible via (1)-(3). The reason is that
namespaces may remain pinned for completely internal reasons yet are
inaccessible to userspace.

For example, a user namespace my remain pinned by get_cred() calls to
stash the opener's credentials into file->f_cred. As it stands file
handles allow to resurrect such a users namespace even though this
should not be possible via (1)-(3). This is a fundamental uapi change
that we shouldn't do if we don't have to.

Consider the following insane case: Various architectures support the
CONFIG_MMU_LAZY_TLB_REFCOUNT option which uses lazy TLB destruction.
When this option is set a userspace task's struct mm_struct may be used
for kernel threads such as the idle task and will only be destroyed once
the cpu's runqueue switches back to another task. But because of ptrace()
permission checks struct mm_struct stashes the user namespace of the
task that struct mm_struct originally belonged to. The kernel thread
will take a reference on the struct mm_struct and thus pin it.

So on an idle system user namespaces can be persisted for arbitrary
amounts of time which also means that they can be resurrected using
namespace file handles. That makes no sense whatsoever. The problem is
of course excarabted on large systems with a huge number of cpus.

To handle this nicely we introduce an active reference count which
tracks (1)-(3). This is easy to do as all of these things are already
managed centrally. Only (1)-(3) will count towards the active reference
count and only namespaces which are active may be opened via namespace
file handles.

The problem is that namespaces may be resurrected. Which means that they
can become temporarily inactive and will be reactived some time later.
Currently the only example of this is the SIOGCSKNS socket ioctl. The
SIOCGSKNS ioctl allows to open a network namespace file descriptor based
on a socket file descriptor.

If a socket is tied to a network namespace that subsequently becomes
inactive but that socket is persisted by another process in another
network namespace (e.g., via SCM_RIGHTS of pidfd_getfd()) then the
SIOCGSKNS ioctl will resurrect this network namespace.

So calls to open_related_ns() and open_namespace() will end up
resurrecting the corresponding namespace tree.

Note that the active reference count does not regulate the lifetime of
the namespace itself. This is still done by the normal reference count.
The active reference count can only be elevated if the regular reference
count is elevated.

The active reference count also doesn't regulate the presence of a
namespace on the namespace trees. It only regulates its visiblity to
namespace file handles (and in later patches to listns()).

A namespace remains on the namespace trees from creation until its
actual destruction. This will allow the kernel to always reach any
namespace trivially and it will also enable subsystems like bpf to walk
the namespace lists on the system for tracing or general introspection
purposes.

Note that different namespaces have different visibility lifetimes on
current kernels. While most namespace are immediately released when the
last task using them exits, the user- and pid namespace are persisted
and thus both remain accessible via /proc/<pid>/ns/<ns_type>.

The user namespace lifetime is aliged with struct cred and is only
released through exit_creds(). However, it becomes inaccessible to
userspace once the last task using it is reaped, i.e., when
release_task() is called and all proc entries are flushed. Similarly,
the pid namespace is also visible until the last task using it has been
reaped and the associated pid numbers are freed.

The active reference counts of the user- and pid namespace are
decremented once the task is reaped.

Based on the namespace trees and the active reference count, a new
listns() system call that allows userspace to iterate through namespaces
in the system. This provides a programmatic interface to discover and
inspect namespaces, enhancing existing namespace apis.

Currently, there is no direct way for userspace to enumerate namespaces
in the system. Applications must resort to scanning /proc/<pid>/ns/
across all processes, which is:

1. Inefficient - requires iterating over all processes
2. Incomplete - misses inactive namespaces that aren't attached to any
   running process but are kept alive by file descriptors, bind mounts,
   or parent namespace references
3. Permission-heavy - requires access to /proc for many processes
4. No ordering or ownership.
5. No filtering per namespace type: Must always iterate and check all
   namespaces.

The list goes on. The listns() system call solves these problems by
providing direct kernel-level enumeration of namespaces. It is similar
to listmount() but obviously tailored to namespaces.

/*
 * @req: Pointer to struct ns_id_req specifying search parameters
 * @ns_ids: User buffer to receive namespace IDs
 * @nr_ns_ids: Size of ns_ids buffer (maximum number of IDs to return)
 * @flags: Reserved for future use (must be 0)
 */
ssize_t listns(const struct ns_id_req *req, u64 *ns_ids,
               size_t nr_ns_ids, unsigned int flags);

Returns:
- On success: Number of namespace IDs written to ns_ids
- On error: Negative error code

/*
 * @size: Structure size
 * @ns_id: Starting point for iteration; use 0 for first call, then
 *         use the last returned ID for subsequent calls to paginate
 * @ns_type: Bitmask of namespace types to include (from enum ns_type):
 *           0: Return all namespace types
 *           MNT_NS: Mount namespaces
 *           NET_NS: Network namespaces
 *           USER_NS: User namespaces
 *           etc. Can be OR'd together
 * @user_ns_id: Filter results to namespaces owned by this user namespace:
 *              0: Return all namespaces (subject to permission checks)
 *              LISTNS_CURRENT_USER: Namespaces owned by caller's user namespace
 *              Other value: Namespaces owned by the specified user namespace ID
 */
struct ns_id_req {
        __u32 size;         /* sizeof(struct ns_id_req) */
        __u32 spare;        /* Reserved, must be 0 */
        __u64 ns_id;        /* Last seen namespace ID (for pagination) */
        __u32 ns_type;      /* Filter by namespace type(s) */
        __u32 spare2;       /* Reserved, must be 0 */
        __u64 user_ns_id;   /* Filter by owning user namespace */
};

Example 1: List all namespaces

void list_all_namespaces(void)
{
struct ns_id_req req = {
.size = sizeof(req),
.ns_id = 0,      /* Start from beginning */
.ns_type = 0,    /* All types */
.user_ns_id = 0, /* All user namespaces */
};
uint64_t ids[100];
ssize_t ret;

printf("All namespaces in the system:\n");
do {
ret = listns(&req, ids, 100, 0);
if (ret < 0) {
perror("listns");
break;
}

for (ssize_t i = 0; i < ret; i++)
printf("  Namespace ID: %llu\n", (unsigned long long)ids[i]);

/* Continue from last seen ID */
if (ret > 0)
req.ns_id = ids[ret - 1];
} while (ret == 100); /* Buffer was full, more may exist */
}

Example 2 : List network namespaces only

void list_network_namespaces(void)
{
struct ns_id_req req = {
.size = sizeof(req),
.ns_id = 0,
.ns_type = NET_NS, /* Only network namespaces */
.user_ns_id = 0,
};
uint64_t ids[100];
ssize_t ret;

ret = listns(&req, ids, 100, 0);
if (ret < 0) {
perror("listns");
return;
}

printf("Network namespaces: %zd found\n", ret);
for (ssize_t i = 0; i < ret; i++)
printf("  netns ID: %llu\n", (unsigned long long)ids[i]);
}

Example 3 : List namespaces owned by current user namespace

void list_owned_namespaces(void)
{
struct ns_id_req req = {
.size = sizeof(req),
.ns_id = 0,
.ns_type = 0,                      /* All types */
.user_ns_id = LISTNS_CURRENT_USER, /* Current userns */
};
uint64_t ids[100];
ssize_t ret;

ret = listns(&req, ids, 100, 0);
if (ret < 0) {
perror("listns");
return;
}

printf("Namespaces owned by my user namespace: %zd\n", ret);
for (ssize_t i = 0; i < ret; i++)
printf("  ns ID: %llu\n", (unsigned long long)ids[i]);
}

Example 4 : List multiple namespace types

void list_network_and_mount_namespaces(void)
{
struct ns_id_req req = {
.size = sizeof(req),
.ns_id = 0,
.ns_type = NET_NS | MNT_NS, /* Network and mount */
.user_ns_id = 0,
};
uint64_t ids[100];
ssize_t ret;

ret = listns(&req, ids, 100, 0);
printf("Network and mount namespaces: %zd found\n", ret);
}

Example 5 : Pagination through large namespace sets

void list_all_with_pagination(void)
{
struct ns_id_req req = {
.size = sizeof(req),
.ns_id = 0,
.ns_type = 0,
.user_ns_id = 0,
};
uint64_t ids[50];
size_t total = 0;
ssize_t ret;

printf("Enumerating all namespaces with pagination:\n");

while (1) {
ret = listns(&req, ids, 50, 0);
if (ret < 0) {
perror("listns");
break;
}
if (ret == 0)
break; /* No more namespaces */

total += ret;
printf("  Batch: %zd namespaces\n", ret);

/* Last ID in this batch becomes start of next batch */
req.ns_id = ids[ret - 1];

if (ret < 50)
break; /* Partial batch = end of results */
}

printf("Total: %zu namespaces\n", total);
}

listns() respects namespace isolation and capabilities:

(1) Global listing (user_ns_id = 0):
    - Requires CAP_SYS_ADMIN in the namespace's owning user namespace
    - OR the namespace must be in the caller's namespace context (e.g.,
      a namespace the caller is currently using)
    - User namespaces additionally allow listing if the caller has
      CAP_SYS_ADMIN in that user namespace itself
(2) Owner-filtered listing (user_ns_id != 0):
    - Requires CAP_SYS_ADMIN in the specified owner user namespace
    - OR the namespace must be in the caller's namespace context
    - This allows unprivileged processes to enumerate namespaces they own
(3) Visibility:
    - Only "active" namespaces are listed
    - A namespace is active if it has a non-zero __ns_ref_active count
    - This includes namespaces used by running processes, held by open
      file descriptors, or kept active by bind mounts
    - Inactive namespaces (kept alive only by internal kernel
      references) are not visible via listns()

* patches from https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-0-2e6f823ebdc0@kernel.org: (74 commits)
  selftests/namespace: test listns() pagination
  selftests/namespace: add stress test
  selftests/namespace: commit_creds() active reference tests
  selftests/namespace: third threaded active reference count test
  selftests/namespace: second threaded active reference count test
  selftests/namespace: first threaded active reference count test
  selftests/namespaces: twelth inactive namespace resurrection test
  selftests/namespaces: eleventh inactive namespace resurrection test
  selftests/namespaces: tenth inactive namespace resurrection test
  selftests/namespaces: ninth inactive namespace resurrection test
  selftests/namespaces: eigth inactive namespace resurrection test
  selftests/namespaces: seventh inactive namespace resurrection test
  selftests/namespaces: sixth inactive namespace resurrection test
  selftests/namespaces: fifth inactive namespace resurrection test
  selftests/namespaces: fourth inactive namespace resurrection test
  selftests/namespaces: third inactive namespace resurrection test
  selftests/namespaces: second inactive namespace resurrection test
  selftests/namespaces: first inactive namespace resurrection test
  selftests/namespaces: seventh listns() permission test
  selftests/namespaces: sixth listns() permission test
  ...

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-0-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: test listns() pagination
Christian Brauner [Wed, 29 Oct 2025 12:21:25 +0000 (13:21 +0100)] 
selftests/namespace: test listns() pagination

Minimal test case to reproduce KASAN out-of-bounds in listns pagination.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-72-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: add stress test
Christian Brauner [Wed, 29 Oct 2025 12:21:24 +0000 (13:21 +0100)] 
selftests/namespace: add stress test

Stress tests for namespace active reference counting.

These tests validate that the active reference counting system can
handle high load scenarios including rapid namespace
creation/destruction, large numbers of concurrent namespaces, and
various edge cases under stress.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-71-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: commit_creds() active reference tests
Christian Brauner [Wed, 29 Oct 2025 12:21:23 +0000 (13:21 +0100)] 
selftests/namespace: commit_creds() active reference tests

Test credential changes and their impact on namespace active references.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-70-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: third threaded active reference count test
Christian Brauner [Wed, 29 Oct 2025 12:21:22 +0000 (13:21 +0100)] 
selftests/namespace: third threaded active reference count test

Test that namespaces become inactive after subprocess with multiple
threads exits. Create a subprocess that unshares user and network
namespaces, then creates two threads that share those namespaces. Verify
that after all threads and subprocess exit, the namespaces are no longer
listed by listns() and cannot be opened by open_by_handle_at().

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-69-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: second threaded active reference count test
Christian Brauner [Wed, 29 Oct 2025 12:21:21 +0000 (13:21 +0100)] 
selftests/namespace: second threaded active reference count test

Test that a namespace remains active while a thread holds an fd to it.
Even after the thread exits, the namespace should remain active as long
as another thread holds a file descriptor to it.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-68-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespace: first threaded active reference count test
Christian Brauner [Wed, 29 Oct 2025 12:21:20 +0000 (13:21 +0100)] 
selftests/namespace: first threaded active reference count test

Test that namespace becomes inactive after thread exits. This verifies
active reference counting works with threads, not just processes.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-67-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: twelth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:19 +0000 (13:21 +0100)] 
selftests/namespaces: twelth inactive namespace resurrection test

Test multi-level namespace resurrection across three user namespace levels.

This test creates a complex namespace hierarchy with three levels of user
namespaces and a network namespace at the deepest level. It verifies that
the resurrection semantics work correctly when SIOCGSKNS is called on a
socket from an inactive namespace tree, and that listns() and
open_by_handle_at() correctly respect visibility rules.

Hierarchy after child processes exit (all with 0 active refcount):

         net_L3A (0)                <- Level 3 network namespace
             |
             +
         userns_L3 (0)              <- Level 3 user namespace
             |
             +
         userns_L2 (0)              <- Level 2 user namespace
             |
             +
         userns_L1 (0)              <- Level 1 user namespace
             |
             x
         init_user_ns

The test verifies:
1. SIOCGSKNS on a socket from inactive net_L3A resurrects the entire chain
2. After resurrection, all namespaces are visible in listns()
3. Resurrected namespaces can be reopened via file handles
4. Closing the netns FD cascades down: the entire ownership chain
   (userns_L3 -> userns_L2 -> userns_L1) becomes inactive again
5. Inactive namespaces disappear from listns() and cannot be reopened
6. Calling SIOCGSKNS again on the same socket resurrects the tree again
7. After second resurrection, namespaces are visible and can be reopened

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-66-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: eleventh inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:18 +0000 (13:21 +0100)] 
selftests/namespaces: eleventh inactive namespace resurrection test

Test combined listns() and file handle operations with socket-kept
netns. Create a netns, keep it alive with a socket, verify it appears in
listns(), then reopen it via file handle obtained from listns() entry.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-65-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: tenth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:17 +0000 (13:21 +0100)] 
selftests/namespaces: tenth inactive namespace resurrection test

Test that socket-kept netns can be reopened via file handle.
Verify that a network namespace kept alive by a socket FD can be
reopened using file handles even after the creating process exits.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-64-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: ninth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:16 +0000 (13:21 +0100)] 
selftests/namespaces: ninth inactive namespace resurrection test

Test that socket-kept netns appears in listns() output.
Verify that a network namespace kept alive by a socket FD appears in
listns() output even after the creating process exits, and that it
disappears when the socket is closed.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-63-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: eigth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:15 +0000 (13:21 +0100)] 
selftests/namespaces: eigth inactive namespace resurrection test

Test IPv6 sockets also work with SIOCGSKNS.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-62-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: seventh inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:14 +0000 (13:21 +0100)] 
selftests/namespaces: seventh inactive namespace resurrection test

Test socket keeps netns active after creating process exits. Verify that
as long as the socket FD exists, the namespace remains active.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-61-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: sixth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:13 +0000 (13:21 +0100)] 
selftests/namespaces: sixth inactive namespace resurrection test

Test multiple sockets keep the same network namespace active. Create
multiple sockets, verify closing some doesn't affect others.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-60-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fifth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:12 +0000 (13:21 +0100)] 
selftests/namespaces: fifth inactive namespace resurrection test

Test SIOCGSKNS fails on non-socket file descriptors.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-59-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fourth inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:11 +0000 (13:21 +0100)] 
selftests/namespaces: fourth inactive namespace resurrection test

Test SIOCGSKNS across setns. Create a socket in netns A, switch to netns
B, verify SIOCGSKNS still returns netns A.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-58-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: third inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:10 +0000 (13:21 +0100)] 
selftests/namespaces: third inactive namespace resurrection test

Test SIOCGSKNS with different socket types (TCP, UDP, RAW).

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-57-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: second inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:09 +0000 (13:21 +0100)] 
selftests/namespaces: second inactive namespace resurrection test

Test that socket file descriptors keep network namespaces active. Create
a network namespace, create a socket in it, then exit the namespace. The
namespace should remain active while the socket FD is held.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-56-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: first inactive namespace resurrection test
Christian Brauner [Wed, 29 Oct 2025 12:21:08 +0000 (13:21 +0100)] 
selftests/namespaces: first inactive namespace resurrection test

Test basic SIOCGSKNS functionality. Create a socket and verify SIOCGSKNS
returns the correct network namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-55-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: seventh listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:07 +0000 (13:21 +0100)] 
selftests/namespaces: seventh listns() permission test

Test that dropping CAP_SYS_ADMIN restricts what we can see.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-54-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: sixth listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:06 +0000 (13:21 +0100)] 
selftests/namespaces: sixth listns() permission test

Test that we can see user namespaces we have CAP_SYS_ADMIN inside of.
This is different from seeing namespaces owned by a user namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-53-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fifth listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:05 +0000 (13:21 +0100)] 
selftests/namespaces: fifth listns() permission test

Test that CAP_SYS_ADMIN in parent user namespace allows seeing
child user namespace's owned namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-52-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fourth listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:04 +0000 (13:21 +0100)] 
selftests/namespaces: fourth listns() permission test

Test permission checking with LISTNS_CURRENT_USER.
Verify that listing with LISTNS_CURRENT_USER respects permissions.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-51-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: third listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:03 +0000 (13:21 +0100)] 
selftests/namespaces: third listns() permission test

Test that users cannot see namespaces from unrelated user namespaces.
Create two sibling user namespaces, verify they can't see each other's
owned namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-50-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: second listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:02 +0000 (13:21 +0100)] 
selftests/namespaces: second listns() permission test

Test that users with CAP_SYS_ADMIN in a user namespace can see
all namespaces owned by that user namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-49-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: first listns() permission test
Christian Brauner [Wed, 29 Oct 2025 12:21:01 +0000 (13:21 +0100)] 
selftests/namespaces: first listns() permission test

Test that unprivileged users can only see namespaces they're currently
in. Create a namespace, drop privileges, verify we can only see our own
namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-48-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: ninth listns() test
Christian Brauner [Wed, 29 Oct 2025 12:21:00 +0000 (13:21 +0100)] 
selftests/namespaces: ninth listns() test

Test error cases for listns().

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-47-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: eigth listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:59 +0000 (13:20 +0100)] 
selftests/namespaces: eigth listns() test

Test that hierarchical active reference propagation keeps parent
user namespaces visible in listns().

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-46-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: seventh listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:58 +0000 (13:20 +0100)] 
selftests/namespaces: seventh listns() test

Test listns() with multiple namespace types filter.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-45-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: sixth listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:57 +0000 (13:20 +0100)] 
selftests/namespaces: sixth listns() test

Test listns() with specific user namespace ID.
Create a user namespace and list namespaces it owns.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-44-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fifth listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:56 +0000 (13:20 +0100)] 
selftests/namespaces: fifth listns() test

Test that listns() only returns active namespaces.
Create a namespace, let it become inactive, verify it's not listed.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-43-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fourth listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:55 +0000 (13:20 +0100)] 
selftests/namespaces: fourth listns() test

Test listns() with LISTNS_CURRENT_USER.
List namespaces owned by current user namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-42-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: third listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:54 +0000 (13:20 +0100)] 
selftests/namespaces: third listns() test

Test listns() pagination.
List namespaces in batches.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-41-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: second listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:53 +0000 (13:20 +0100)] 
selftests/namespaces: second listns() test

test listns() with type filtering.
List only network namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-40-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: first listns() test
Christian Brauner [Wed, 29 Oct 2025 12:20:52 +0000 (13:20 +0100)] 
selftests/namespaces: first listns() test

Test basic listns() functionality with the unified namespace tree.
List all active namespaces globally.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-39-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: add listns() wrapper
Christian Brauner [Wed, 29 Oct 2025 12:20:51 +0000 (13:20 +0100)] 
selftests/namespaces: add listns() wrapper

Add a wrapper for the listns() system call.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-38-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fifteenth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:50 +0000 (13:20 +0100)] 
selftests/namespaces: fifteenth active reference count tests

Test different namespace types (net, uts, ipc) all contributing
active references to the same owning user namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-37-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fourteenth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:49 +0000 (13:20 +0100)] 
selftests/namespaces: fourteenth active reference count tests

Test that user namespace as a child also propagates correctly.
Create user_A -> user_B, verify when user_B is active that user_A
is also active. This is different from non-user namespace children.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-36-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: thirteenth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:48 +0000 (13:20 +0100)] 
selftests/namespaces: thirteenth active reference count tests

Test that parent stays active as long as ANY child is active.
Create parent user namespace with two child net namespaces.
Parent should remain active until BOTH children are inactive.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-35-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: twelth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:47 +0000 (13:20 +0100)] 
selftests/namespaces: twelth active reference count tests

Test hierarchical propagation with deep namespace hierarchy.
Create: init_user_ns -> user_A -> user_B -> net_ns
When net_ns is active, both user_A and user_B should be active.
This verifies the conditional recursion in __ns_ref_active_put() works.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-34-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: eleventh active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:46 +0000 (13:20 +0100)] 
selftests/namespaces: eleventh active reference count tests

Test that different namespace types with same owner all contribute
active references to the owning user namespace.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-33-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: tenth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:45 +0000 (13:20 +0100)] 
selftests/namespaces: tenth active reference count tests

Test multiple children sharing same parent.
Parent should stay active as long as ANY child is active.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-32-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: ninth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:44 +0000 (13:20 +0100)] 
selftests/namespaces: ninth active reference count tests

Test multi-level hierarchy (3+ levels deep).
Grandparent â†’ Parent â†’ Child
When child is active, both parent AND grandparent should be active.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-31-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: eigth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:43 +0000 (13:20 +0100)] 
selftests/namespaces: eigth active reference count tests

Test that bind mounts keep namespaces in the tree even when inactive

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-30-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: seventh active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:42 +0000 (13:20 +0100)] 
selftests/namespaces: seventh active reference count tests

Test hierarchical active reference propagation.
When a child namespace is active, its owning user namespace should also
be active automatically due to hierarchical active reference propagation.
This ensures parents are always reachable when children are active.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-29-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: sixth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:41 +0000 (13:20 +0100)] 
selftests/namespaces: sixth active reference count tests

Test that an open file descriptor keeps a namespace active.
Even after the creating process exits, the namespace should remain
active as long as an fd is held open.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-28-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fifth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:40 +0000 (13:20 +0100)] 
selftests/namespaces: fifth active reference count tests

Test PID namespace active ref tracking

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-27-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: fourth active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:39 +0000 (13:20 +0100)] 
selftests/namespaces: fourth active reference count tests

Test user namespace active ref tracking via credential lifecycle.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-26-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: third active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:38 +0000 (13:20 +0100)] 
selftests/namespaces: third active reference count tests

Test that a namespace remains active while a process is using it,
even after the creating process exits.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-25-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: second active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:37 +0000 (13:20 +0100)] 
selftests/namespaces: second active reference count tests

Test namespace lifecycle: create a namespace in a child process, get a
file handle while it's active, then try to reopen after the process
exits (namespace becomes inactive).

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-24-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/namespaces: first active reference count tests
Christian Brauner [Wed, 29 Oct 2025 12:20:36 +0000 (13:20 +0100)] 
selftests/namespaces: first active reference count tests

Test that initial namespaces can be reopened via file handle. Initial
namespaces should always have a ref count of one from boot.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-23-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoselftests/filesystems: remove CLONE_NEWPIDNS from setup_userns() helper
Christian Brauner [Wed, 29 Oct 2025 12:20:35 +0000 (13:20 +0100)] 
selftests/filesystems: remove CLONE_NEWPIDNS from setup_userns() helper

This is effectively unused and doesn't really server any purpose after
having reviewed all of the tests that rely on it.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-22-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonsfs: update tools header
Christian Brauner [Wed, 29 Oct 2025 12:20:34 +0000 (13:20 +0100)] 
nsfs: update tools header

Ensure all the new uapi bits are visible for the selftests.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-21-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agoarch: hookup listns() system call
Christian Brauner [Wed, 29 Oct 2025 12:20:33 +0000 (13:20 +0100)] 
arch: hookup listns() system call

Add the listns() system call to all architectures.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-20-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Arnd Bergmann <arnd@arndb.de>
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: add listns()
Christian Brauner [Wed, 29 Oct 2025 12:20:32 +0000 (13:20 +0100)] 
nstree: add listns()

Add a new listns() system call that allows userspace to iterate through
namespaces in the system. This provides a programmatic interface to
discover and inspect namespaces, enhancing existing namespace apis.

Currently, there is no direct way for userspace to enumerate namespaces
in the system. Applications must resort to scanning /proc/<pid>/ns/
across all processes, which is:

1. Inefficient - requires iterating over all processes
2. Incomplete - misses inactive namespaces that aren't attached to any
   running process but are kept alive by file descriptors, bind mounts,
   or parent namespace references
3. Permission-heavy - requires access to /proc for many processes
4. No ordering or ownership.
5. No filtering per namespace type: Must always iterate and check all
   namespaces.

The list goes on. The listns() system call solves these problems by
providing direct kernel-level enumeration of namespaces. It is similar
to listmount() but obviously tailored to namespaces.

/*
 * @req: Pointer to struct ns_id_req specifying search parameters
 * @ns_ids: User buffer to receive namespace IDs
 * @nr_ns_ids: Size of ns_ids buffer (maximum number of IDs to return)
 * @flags: Reserved for future use (must be 0)
 */
ssize_t listns(const struct ns_id_req *req, u64 *ns_ids,
               size_t nr_ns_ids, unsigned int flags);

Returns:
- On success: Number of namespace IDs written to ns_ids
- On error: Negative error code

/*
 * @size: Structure size
 * @ns_id: Starting point for iteration; use 0 for first call, then
 *         use the last returned ID for subsequent calls to paginate
 * @ns_type: Bitmask of namespace types to include (from enum ns_type):
 *           0: Return all namespace types
 *           MNT_NS: Mount namespaces
 *           NET_NS: Network namespaces
 *           USER_NS: User namespaces
 *           etc. Can be OR'd together
 * @user_ns_id: Filter results to namespaces owned by this user namespace:
 *              0: Return all namespaces (subject to permission checks)
 *              LISTNS_CURRENT_USER: Namespaces owned by caller's user namespace
 *              Other value: Namespaces owned by the specified user namespace ID
 */
struct ns_id_req {
        __u32 size;         /* sizeof(struct ns_id_req) */
        __u32 spare;        /* Reserved, must be 0 */
        __u64 ns_id;        /* Last seen namespace ID (for pagination) */
        __u32 ns_type;      /* Filter by namespace type(s) */
        __u32 spare2;       /* Reserved, must be 0 */
        __u64 user_ns_id;   /* Filter by owning user namespace */
};

Example 1: List all namespaces

void list_all_namespaces(void)
{
    struct ns_id_req req = {
        .size = sizeof(req),
        .ns_id = 0,          /* Start from beginning */
        .ns_type = 0,        /* All types */
        .user_ns_id = 0,     /* All user namespaces */
    };
    uint64_t ids[100];
    ssize_t ret;

    printf("All namespaces in the system:\n");
    do {
        ret = listns(&req, ids, 100, 0);
        if (ret < 0) {
            perror("listns");
            break;
        }

        for (ssize_t i = 0; i < ret; i++)
            printf("  Namespace ID: %llu\n", (unsigned long long)ids[i]);

        /* Continue from last seen ID */
        if (ret > 0)
            req.ns_id = ids[ret - 1];
    } while (ret == 100);  /* Buffer was full, more may exist */
}

Example 2: List network namespaces only

void list_network_namespaces(void)
{
    struct ns_id_req req = {
        .size = sizeof(req),
        .ns_id = 0,
        .ns_type = NET_NS,   /* Only network namespaces */
        .user_ns_id = 0,
    };
    uint64_t ids[100];
    ssize_t ret;

    ret = listns(&req, ids, 100, 0);
    if (ret < 0) {
        perror("listns");
        return;
    }

    printf("Network namespaces: %zd found\n", ret);
    for (ssize_t i = 0; i < ret; i++)
        printf("  netns ID: %llu\n", (unsigned long long)ids[i]);
}

Example 3: List namespaces owned by current user namespace

void list_owned_namespaces(void)
{
    struct ns_id_req req = {
        .size = sizeof(req),
        .ns_id = 0,
        .ns_type = 0,                      /* All types */
        .user_ns_id = LISTNS_CURRENT_USER, /* Current userns */
    };
    uint64_t ids[100];
    ssize_t ret;

    ret = listns(&req, ids, 100, 0);
    if (ret < 0) {
        perror("listns");
        return;
    }

    printf("Namespaces owned by my user namespace: %zd\n", ret);
    for (ssize_t i = 0; i < ret; i++)
        printf("  ns ID: %llu\n", (unsigned long long)ids[i]);
}

Example 4: List multiple namespace types

void list_network_and_mount_namespaces(void)
{
    struct ns_id_req req = {
        .size = sizeof(req),
        .ns_id = 0,
        .ns_type = NET_NS | MNT_NS,  /* Network and mount */
        .user_ns_id = 0,
    };
    uint64_t ids[100];
    ssize_t ret;

    ret = listns(&req, ids, 100, 0);
    printf("Network and mount namespaces: %zd found\n", ret);
}

Example 5: Pagination through large namespace sets

void list_all_with_pagination(void)
{
    struct ns_id_req req = {
        .size = sizeof(req),
        .ns_id = 0,
        .ns_type = 0,
        .user_ns_id = 0,
    };
    uint64_t ids[50];
    size_t total = 0;
    ssize_t ret;

    printf("Enumerating all namespaces with pagination:\n");

    while (1) {
        ret = listns(&req, ids, 50, 0);
        if (ret < 0) {
            perror("listns");
            break;
        }
        if (ret == 0)
            break;  /* No more namespaces */

        total += ret;
        printf("  Batch: %zd namespaces\n", ret);

        /* Last ID in this batch becomes start of next batch */
        req.ns_id = ids[ret - 1];

        if (ret < 50)
            break;  /* Partial batch = end of results */
    }

    printf("Total: %zu namespaces\n", total);
}

Permission Model

listns() respects namespace isolation and capabilities:

(1) Global listing (user_ns_id = 0):
    - Requires CAP_SYS_ADMIN in the namespace's owning user namespace
    - OR the namespace must be in the caller's namespace context (e.g.,
      a namespace the caller is currently using)
    - User namespaces additionally allow listing if the caller has
      CAP_SYS_ADMIN in that user namespace itself
(2) Owner-filtered listing (user_ns_id != 0):
    - Requires CAP_SYS_ADMIN in the specified owner user namespace
    - OR the namespace must be in the caller's namespace context
    - This allows unprivileged processes to enumerate namespaces they own
(3) Visibility:
    - Only "active" namespaces are listed
    - A namespace is active if it has a non-zero __ns_ref_active count
    - This includes namespaces used by running processes, held by open
      file descriptors, or kept active by bind mounts
    - Inactive namespaces (kept alive only by internal kernel
      references) are not visible via listns()

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-19-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: add unified namespace list
Christian Brauner [Wed, 29 Oct 2025 12:20:31 +0000 (13:20 +0100)] 
nstree: add unified namespace list

Allow to walk the unified namespace list completely locklessly.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-18-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: simplify rbtree comparison helpers
Christian Brauner [Wed, 29 Oct 2025 12:20:30 +0000 (13:20 +0100)] 
nstree: simplify rbtree comparison helpers

They all do the same basic thing.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-17-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: maintain list of owned namespaces
Christian Brauner [Wed, 29 Oct 2025 12:20:29 +0000 (13:20 +0100)] 
nstree: maintain list of owned namespaces

The namespace tree doesn't express the ownership concept of namespace
appropriately. Maintain a list of directly owned namespaces per user
namespace. This will allow userspace and the kernel to use the listns()
system call to walk the namespace tree by owning user namespace. The
rbtree is used to find the relevant namespace entry point which allows
to continue iteration and the owner list can be used to walk the tree
completely lock free.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-16-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: assign fixed ids to the initial namespaces
Christian Brauner [Wed, 29 Oct 2025 12:20:28 +0000 (13:20 +0100)] 
nstree: assign fixed ids to the initial namespaces

The initial set of namespace comes with fixed inode numbers making it
easy for userspace to identify them solely based on that information.
This has long preceeded anything here.

Similarly, let's assign fixed namespace ids for the initial namespaces.

Kill the cookie and use a sequentially increasing number. This has the
nice side-effect that the owning user namespace will always have a
namespace id that is smaller than any of it's descendant namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-15-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: allow lookup solely based on inode
Christian Brauner [Wed, 29 Oct 2025 12:20:27 +0000 (13:20 +0100)] 
nstree: allow lookup solely based on inode

The namespace file handle struct nsfs_file_handle is uapi and userspace
is expressly allowed to generate file handles without going through
name_to_handle_at().

Allow userspace to generate a file handle where both the inode number
and the namespace type are zero and just pass in the unique namespace
id. The kernel uses the unified namespace tree to find the namespace and
open the file handle.

When the kernel creates a file handle via name_to_handle_at() it will
always fill in the type and the inode number allowing userspace to
retrieve core information.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-14-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: introduce a unified tree
Christian Brauner [Wed, 29 Oct 2025 12:20:26 +0000 (13:20 +0100)] 
nstree: introduce a unified tree

This will allow userspace to lookup and stat a namespace simply by its
identifier without having to know what type of namespace it is.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-13-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: use anonymous struct to group list member
Christian Brauner [Wed, 29 Oct 2025 12:20:25 +0000 (13:20 +0100)] 
ns: use anonymous struct to group list member

Make it easier to spot that they belong together conceptually.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-12-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: add active reference count
Christian Brauner [Wed, 29 Oct 2025 12:20:24 +0000 (13:20 +0100)] 
ns: add active reference count

The namespace tree is, among other things, currently used to support
file handles for namespaces. When a namespace is created it is placed on
the namespace trees and when it is destroyed it is removed from the
namespace trees.

While a namespace is on the namespace trees with a valid reference count
it is possible to reopen it through a namespace file handle. This is all
fine but has some issues that should be addressed.

On current kernels a namespace is visible to userspace in the
following cases:

(1) The namespace is in use by a task.
(2) The namespace is persisted through a VFS object (namespace file
    descriptor or bind-mount).
    Note that (2) only cares about direct persistence of the namespace
    itself not indirectly via e.g., file->f_cred file references or
    similar.
(3) The namespace is a hierarchical namespace type and is the parent of
    a single or multiple child namespaces.

Case (3) is interesting because it is possible that a parent namespace
might not fulfill any of (1) or (2), i.e., is invisible to userspace but
it may still be resurrected through the NS_GET_PARENT ioctl().

Currently namespace file handles allow much broader access to namespaces
than what is currently possible via (1)-(3). The reason is that
namespaces may remain pinned for completely internal reasons yet are
inaccessible to userspace.

For example, a user namespace my remain pinned by get_cred() calls to
stash the opener's credentials into file->f_cred. As it stands file
handles allow to resurrect such a users namespace even though this
should not be possible via (1)-(3). This is a fundamental uapi change
that we shouldn't do if we don't have to.

Consider the following insane case: Various architectures support the
CONFIG_MMU_LAZY_TLB_REFCOUNT option which uses lazy TLB destruction.
When this option is set a userspace task's struct mm_struct may be used
for kernel threads such as the idle task and will only be destroyed once
the cpu's runqueue switches back to another task. But because of ptrace()
permission checks struct mm_struct stashes the user namespace of the
task that struct mm_struct originally belonged to. The kernel thread
will take a reference on the struct mm_struct and thus pin it.

So on an idle system user namespaces can be persisted for arbitrary
amounts of time which also means that they can be resurrected using
namespace file handles. That makes no sense whatsoever. The problem is
of course excarabted on large systems with a huge number of cpus.

To handle this nicely we introduce an active reference count which
tracks (1)-(3). This is easy to do as all of these things are already
managed centrally. Only (1)-(3) will count towards the active reference
count and only namespaces which are active may be opened via namespace
file handles.

The problem is that namespaces may be resurrected. Which means that they
can become temporarily inactive and will be reactived some time later.
Currently the only example of this is the SIOGCSKNS socket ioctl. The
SIOCGSKNS ioctl allows to open a network namespace file descriptor based
on a socket file descriptor.

If a socket is tied to a network namespace that subsequently becomes
inactive but that socket is persisted by another process in another
network namespace (e.g., via SCM_RIGHTS of pidfd_getfd()) then the
SIOCGSKNS ioctl will resurrect this network namespace.

So calls to open_related_ns() and open_namespace() will end up
resurrecting the corresponding namespace tree.

Note that the active reference count does not regulate the lifetime of
the namespace itself. This is still done by the normal reference count.
The active reference count can only be elevated if the regular reference
count is elevated.

The active reference count also doesn't regulate the presence of a
namespace on the namespace trees. It only regulates its visiblity to
namespace file handles (and in later patches to listns()).

A namespace remains on the namespace trees from creation until its
actual destruction. This will allow the kernel to always reach any
namespace trivially and it will also enable subsystems like bpf to walk
the namespace lists on the system for tracing or general introspection
purposes.

Note that different namespaces have different visibility lifetimes on
current kernels. While most namespace are immediately released when the
last task using them exits, the user- and pid namespace are persisted
and thus both remain accessible via /proc/<pid>/ns/<ns_type>.

The user namespace lifetime is aliged with struct cred and is only
released through exit_creds(). However, it becomes inaccessible to
userspace once the last task using it is reaped, i.e., when
release_task() is called and all proc entries are flushed. Similarly,
the pid namespace is also visible until the last task using it has been
reaped and the associated pid numbers are freed.

The active reference counts of the user- and pid namespace are
decremented once the task is reaped.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-11-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: rename to exit_nsproxy_namespaces()
Christian Brauner [Wed, 29 Oct 2025 12:20:23 +0000 (13:20 +0100)] 
ns: rename to exit_nsproxy_namespaces()

The current naming is very misleading as this really isn't exiting all
of the task's namespaces. It is only exiting the namespaces that hang of
off nsproxy. Reflect that in the name.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-10-2e6f823ebdc0@kernel.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: add __ns_ref_read()
Christian Brauner [Wed, 29 Oct 2025 12:20:22 +0000 (13:20 +0100)] 
ns: add __ns_ref_read()

Implement ns_ref_read() the same way as ns_ref_{get,put}().
No point in making that any more special or different from the other
helpers.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-9-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: initialize ns_list_node for initial namespaces
Christian Brauner [Wed, 29 Oct 2025 12:20:21 +0000 (13:20 +0100)] 
ns: initialize ns_list_node for initial namespaces

Make sure that the list is always initialized for initial namespaces.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-8-2e6f823ebdc0@kernel.org
Fixes: 885fc8ac0a4d ("nstree: make iterator generic")
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: use NS_COMMON_INIT() for all namespaces
Christian Brauner [Mon, 3 Nov 2025 15:16:01 +0000 (16:16 +0100)] 
ns: use NS_COMMON_INIT() for all namespaces

Now that we have a common initializer use it for all static namespaces.

Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: add NS_COMMON_INIT()
Christian Brauner [Mon, 3 Nov 2025 15:10:10 +0000 (16:10 +0100)] 
ns: add NS_COMMON_INIT()

Add an initializer that can be used for the ns common initialization for
static namespace such as most init namespaces.

Suggested-by: Thomas Gleixner <tglx@linutronix.de>
Link: https://patch.msgid.link/87ecqhy2y5.ffs@tglx
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agons: add missing authorship
Christian Brauner [Mon, 3 Nov 2025 16:34:18 +0000 (17:34 +0100)] 
ns: add missing authorship

I authored the files a short while ago.

Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonstree: simplify return
Christian Brauner [Wed, 29 Oct 2025 12:20:20 +0000 (13:20 +0100)] 
nstree: simplify return

node_to_ns() checks for NULL and the assert isn't really helpful and
will have to be dropped later anyway.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-7-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agocgroup: add cgroup namespace to tree after owner is set
Christian Brauner [Wed, 29 Oct 2025 12:20:19 +0000 (13:20 +0100)] 
cgroup: add cgroup namespace to tree after owner is set

Otherwise we trip VFS_WARN_ON_ONC() in __ns_tree_add_raw().

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-6-2e6f823ebdc0@kernel.org
Fixes: 7c6059398533 ("cgroup: support ns lookup")
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agonsfs: raise SB_I_NODEV and SB_I_NOEXEC
Christian Brauner [Wed, 29 Oct 2025 12:20:18 +0000 (13:20 +0100)] 
nsfs: raise SB_I_NODEV and SB_I_NOEXEC

There's zero need for nsfs to allow device nodes or execution.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-5-2e6f823ebdc0@kernel.org
Signed-off-by: Christian Brauner <brauner@kernel.org>
4 weeks agopidfs: raise DCACHE_DONTCACHE explicitly
Christian Brauner [Wed, 29 Oct 2025 12:20:17 +0000 (13:20 +0100)] 
pidfs: raise DCACHE_DONTCACHE explicitly

While pidfs dentries are never hashed and thus retain_dentry() will never
consider them for placing them on the LRU it isn't great to always have
to go and remember that. Raise DCACHE_DONTCACHE explicitly as a visual
marker that dentries aren't kept but freed immediately instead.

Link: https://patch.msgid.link/20251029-work-namespace-nstree-listns-v4-4-2e6f823ebdc0@kernel.org
Tested-by: syzbot@syzkaller.appspotmail.com
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Signed-off-by: Christian Brauner <brauner@kernel.org>