[RFC next 2/5] usernamespace: make usernamespace rcu safe
From: Chen Ridong
Date: Fri May 09 2025 - 03:08:37 EST
From: Chen Ridong <chenridong@xxxxxxxxxx>
To ensure a safe top-down iteration, the user namespace should be made
RCU safe. This way, it is safe to iterate over all the child namespaces
of a root namespace while holding an RCU read lock.
Signed-off-by: Chen Ridong <chenridong@xxxxxxxxxx>
---
include/linux/user_namespace.h | 1 +
kernel/user_namespace.c | 12 ++++++++++--
2 files changed, 11 insertions(+), 2 deletions(-)
diff --git a/include/linux/user_namespace.h b/include/linux/user_namespace.h
index 7b1e180227c8..d84b2703caab 100644
--- a/include/linux/user_namespace.h
+++ b/include/linux/user_namespace.h
@@ -80,6 +80,7 @@ struct user_namespace {
struct user_namespace *parent;
struct list_head ns_node;
struct list_head children;
+ struct rcu_head rcu;
int level;
kuid_t owner;
kgid_t group;
diff --git a/kernel/user_namespace.c b/kernel/user_namespace.c
index b570536934cc..cbe8f96c3e60 100644
--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -196,6 +196,15 @@ int unshare_userns(unsigned long unshare_flags, struct cred **new_cred)
return err;
}
+static void __free_user_ns(struct rcu_head *p)
+{
+ struct user_namespace *ns =
+ container_of(p, struct user_namespace, rcu);
+
+ list_del_rcu(&ns->ns_node);
+ kmem_cache_free(user_ns_cachep, ns);
+}
+
static void free_user_ns(struct work_struct *work)
{
struct user_namespace *parent, *ns =
@@ -220,10 +229,9 @@ static void free_user_ns(struct work_struct *work)
kfree(ns->binfmt_misc);
#endif
retire_userns_sysctls(ns);
- list_del_rcu(&ns->ns_node);
key_free_user_ns(ns);
ns_free_inum(&ns->ns);
- kmem_cache_free(user_ns_cachep, ns);
+ call_rcu(&ns->rcu, __free_user_ns);
dec_user_namespaces(ucounts);
ns = parent;
} while (refcount_dec_and_test(&parent->ns.count));
--
2.34.1