[PATCH 2/2] kernfs: RCU free a new node that was already in the idr

From: Josef Bacik

Date: Wed Dec 02 2026 - 11:50:37 EST


kernfs_find_and_get_node_by_id() can read a node after the error path of
__kernfs_new_node() has freed it.

Commit 4207b556e62f ("kernfs: RCU protect kernfs_nodes and avoid
kernfs_idr_lock in kernfs_find_and_get_node_by_id()") moved the lookup
from kernfs_idr_lock to RCU and made kernfs_put() wait for a grace
period. The error path still frees the node right after idr_remove().

Fix by freeing the node with kernfs_free_rcu() there as well.

Fixes: 4207b556e62f ("kernfs: RCU protect kernfs_nodes and avoid kernfs_idr_lock in kernfs_find_and_get_node_by_id()")
Signed-off-by: Josef Bacik <josef@xxxxxxxx>
---
fs/kernfs/dir.c | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/fs/kernfs/dir.c b/fs/kernfs/dir.c
index 9569588aac751..257c6082f1a82 100644
--- a/fs/kernfs/dir.c
+++ b/fs/kernfs/dir.c
@@ -718,14 +718,16 @@ static struct kernfs_node *__kernfs_new_node(struct kernfs_root *root,
err_out4:
RCU_INIT_POINTER(kn->__parent, NULL);
kernfs_put(parent);
- if (kn->iattr) {
+ if (kn->iattr)
simple_xattrs_free(&root->xa_cache, &kn->iattr->xattrs, NULL);
- kmem_cache_free(kernfs_iattrs_cache, kn->iattr);
- }
err_out3:
spin_lock(&root->kernfs_idr_lock);
idr_remove(&root->ino_idr, (u32)kernfs_ino(kn));
spin_unlock(&root->kernfs_idr_lock);
+ /* a lookup by id may still see @kn, this also frees @name and iattr */
+ call_rcu(&kn->rcu, kernfs_free_rcu);
+ return NULL;
+
err_out2:
kmem_cache_free(kernfs_node_cache, kn);
err_out1: