From: Shakeel Butt <shakeel.butt@linux.dev>
To: Christian Brauner <brauner@kernel.org>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>,
Tejun Heo <tj@kernel.org>,
Andrew Morton <akpm@linux-foundation.org>,
Ian Kent <raven@themaw.net>, Jori Koolstra <jkoolstra@xs4all.nl>,
"T . J . Mercier" <tjmercier@google.com>,
Meta kernel team <kernel-team@meta.com>,
cgroups@vger.kernel.org, linux-fsdevel@vger.kernel.org,
driver-core@lists.linux.dev, linux-kernel@vger.kernel.org
Subject: [PATCH 3/3] kernfs: list directories without kernfs_rwsem
Date: Fri, 4 Dec 2026 13:10:32 -0800 [thread overview]
Message-ID: <20261204211034.3436390-4-shakeel.butt@linux.dev> (raw)
In-Reply-To: <20261204211034.3436390-1-shakeel.butt@linux.dev>
kernfs_fop_readdir() takes kernfs_rwsem for reading for each entry.
There is one kernfs_rwsem for the whole hierarchy, so a listing of any
cgroup directory waits whenever a writer anywhere in cgroupfs holds the
lock or waits for it, for example a mkdir that is preempted with the
lock held. Monitors such as oomd and below list cgroup directories all
the time.
List under RCU instead, retrying on the directory's sequence count:
- Each step searches down the tree for the first visible entry after
the last one listed, and copies its name, ino, type and hash in the
same read section. rb_next() is not used, as it follows parent
pointers, which are not safe to follow without the lock.
- The cursor pinned when dir_emit() fails is used only if it is still
in the directory under its current key, which also shows that the
key was read consistently.
- A found entry is pinned with atomic_inc_not_zero(). If its count is
already zero, it has been unlinked and is being freed, and the
listing goes on after it.
- If the directory keeps changing, a step takes kernfs_rwsem after a
few attempts, so that a listing always makes progress.
The listing shows the same entries in the same order as before.
Skipping k hidden entries, dying ones or other namespaces', now takes k
searches, O(k log n) instead of O(k).
A lockless listing may read an entry's namespace up to an RCU grace
period after the entry is removed or renamed into another namespace.
That is safe for network namespaces, the only namespaces kernfs has:
cleanup_net() frees a namespace only in a later run, after the
synchronize_rcu() in ops_undo_list().
In a 16 CPU VM, 8 tasks listed cgroup directories of 36 entries while
a mkdir and rmdir loop ran at SCHED_IDLE on a CPU shared with a busy
loop, so that it was often preempted with the lock held. The slowest
listing went from 271 ms to 188 us, and listings per second from 51k to
1.26M. With 4 mkdir and rmdir loops at normal priority instead, the
readers went from 97k to 1.26M listings per second, and the writers
from 284 to 7440 mkdir and rmdir pairs per second. Listing
/sys/class/net in the root namespace, which skips 1000 devices in other
namespaces, went from 20.5k to 29.6k listings per second.
Signed-off-by: Shakeel Butt <shakeel.butt@linux.dev>
---
fs/kernfs/dir.c | 282 +++++++++++++++++++++++++++++++-----------------
1 file changed, 186 insertions(+), 96 deletions(-)
diff --git a/fs/kernfs/dir.c b/fs/kernfs/dir.c
index 9acefb8713fd..1cc5c10bead5 100644
--- a/fs/kernfs/dir.c
+++ b/fs/kernfs/dir.c
@@ -1964,140 +1964,230 @@ static int kernfs_dir_fop_release(struct inode *inode, struct file *filp)
}
/*
- * Find where a listing left off. @resumed says whether @pos is still that
- * entry; if not, the search falls back to @hash, keyed by @name if given.
+ * The walks below run under RCU, without kernfs_rwsem. They only go down
+ * the tree, which is safe during a change but may then miss an entry, so
+ * the caller retries if @parent->dir.seq changed.
*/
-static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns,
- struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos,
- const char *name, bool *resumed)
+
+/* the child of @parent with the key (@hash, @ns, @name) */
+static struct kernfs_node *kernfs_dir_find_key(struct kernfs_node *parent,
+ unsigned int hash,
+ const struct ns_common *ns,
+ const char *name)
{
- if (resumed)
- *resumed = false;
- if (pos) {
- /*
- * A rename keeps the hash if the new name hashes the same, so
- * check @name too. Otherwise the caller would step over the
- * entry now sitting where @pos used to be.
- */
- int valid = kernfs_active(pos) &&
- rcu_access_pointer(pos->__parent) == parent &&
- hash == pos->hash &&
- (!name || !strcmp(name, kernfs_rcu_name(pos)));
- kernfs_put(pos);
- if (!valid)
- pos = NULL;
- else if (resumed)
- *resumed = true;
+ struct rb_node *node = rcu_dereference_raw(parent->dir.children.rb_node);
+
+ while (node) {
+ struct kernfs_node *kn = rb_to_kn(node);
+ int result = kernfs_name_compare(hash, name, ns, kn);
+
+ if (result < 0)
+ node = rcu_dereference_raw(node->rb_left);
+ else if (result > 0)
+ node = rcu_dereference_raw(node->rb_right);
+ else
+ return kn;
}
- if (!pos && (hash > 1) && (hash < INT_MAX)) {
- struct rb_node *node = parent->dir.children.rb_node;
+ return NULL;
+}
- /*
- * Keep a node only on the way left, so the search ends on the
- * first entry after the key. An empty @name sorts before all
- * entries sharing the hash, so it lands on the first of them.
- */
- while (node) {
- struct kernfs_node *kn = rb_to_kn(node);
-
- if (kernfs_name_compare(hash, name ?: "", ns, kn) < 0) {
- pos = kn;
- node = node->rb_left;
- } else {
- node = node->rb_right;
- }
+/*
+ * The first child of @parent whose key is greater than (@hash, @ns, @name).
+ * An empty @name sorts before every name with the same hash and namespace.
+ */
+static struct kernfs_node *kernfs_dir_entry_after(struct kernfs_node *parent,
+ unsigned int hash,
+ const struct ns_common *ns,
+ const char *name)
+{
+ struct rb_node *node = rcu_dereference_raw(parent->dir.children.rb_node);
+ struct kernfs_node *pos = NULL;
+
+ /* keep a node only on the way left, so the walk ends on the first one */
+ while (node) {
+ struct kernfs_node *kn = rb_to_kn(node);
+
+ if (kernfs_name_compare(hash, name, ns, kn) < 0) {
+ pos = kn;
+ node = rcu_dereference_raw(node->rb_left);
+ } else {
+ node = rcu_dereference_raw(node->rb_right);
}
}
- /* Skip over entries which are dying/dead or in the wrong namespace */
- while (pos && (!kernfs_active(pos) ||
- kernfs_ns_id(pos->ns) != kernfs_ns_id(ns))) {
- struct rb_node *node = rb_next(&pos->rb);
- if (!node)
- pos = NULL;
- else
- pos = rb_to_kn(node);
- }
return pos;
}
-static struct kernfs_node *kernfs_dir_next_pos(const struct ns_common *ns,
- struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos,
- const char *name)
+/*
+ * Like kernfs_dir_entry_after(), but skip the children that a listing in
+ * namespace @ns does not show: dying or dead ones, and other namespaces'.
+ * Gives up early if the tree changed since @seq; the caller retries then.
+ */
+static struct kernfs_node *kernfs_dir_visible_after(struct kernfs_node *parent,
+ const struct ns_common *ns,
+ unsigned int hash,
+ const char *name,
+ unsigned int seq)
{
- bool resumed;
-
- pos = kernfs_dir_pos(ns, parent, hash, pos, name, &resumed);
- /* Step over @pos only if it survived; @name finds the spot if not. */
- if (pos && resumed) {
- do {
- struct rb_node *node = rb_next(&pos->rb);
- if (!node)
- pos = NULL;
- else
- pos = rb_to_kn(node);
- } while (pos && (!kernfs_active(pos) ||
- kernfs_ns_id(pos->ns) != kernfs_ns_id(ns)));
+ struct kernfs_node *pos = kernfs_dir_entry_after(parent, hash, ns, name);
+
+ while (pos && (!__kernfs_active(pos) ||
+ kernfs_ns_id(READ_ONCE(pos->ns)) != kernfs_ns_id(ns))) {
+ if (read_seqcount_retry(&parent->dir.seq, seq))
+ return NULL;
+ pos = kernfs_dir_entry_after(parent, READ_ONCE(pos->hash),
+ READ_ONCE(pos->ns),
+ kernfs_rcu_name(pos));
}
return pos;
}
+/*
+ * Whether @cursor, pinned when the previous call stopped, is still the entry
+ * to list at position @hash: active, in namespace @ns, and still a child of
+ * @parent under the key it has now. Finding it under that key also shows
+ * that the key was read consistently: a rename changes the key only while
+ * the node is out of the tree, and putting it back changes @parent->dir.seq.
+ * The namespace is compared first, so that only @ns is dereferenced: a
+ * renamed cursor's namespace may be gone.
+ */
+static bool kernfs_dir_cursor_valid(struct kernfs_node *parent,
+ struct kernfs_node *cursor,
+ const struct ns_common *ns, loff_t hash)
+{
+ unsigned int cursor_hash = READ_ONCE(cursor->hash);
+
+ return __kernfs_active(cursor) && cursor_hash == hash &&
+ READ_ONCE(cursor->ns) == ns &&
+ kernfs_dir_find_key(parent, cursor_hash, ns,
+ kernfs_rcu_name(cursor)) == cursor;
+}
+
+/*
+ * Lockless attempts at a step before kernfs_fop_readdir() takes kernfs_rwsem
+ * to stop the directory from changing.
+ */
+#define KERNFS_READDIR_TRIES 3
+
static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
{
+ char *buf1 __free(kfree) = NULL;
+ char *buf2 __free(kfree) = NULL;
struct dentry *dentry = file->f_path.dentry;
struct kernfs_node *parent = kernfs_dentry_node(dentry);
- struct kernfs_node *pos = file->private_data;
- char *name __free(kfree) = NULL;
- struct kernfs_root *root;
+ struct kernfs_node *cursor = file->private_data;
const struct ns_common *ns = NULL;
+ unsigned int key_hash = 0;
+ char *name, *key = NULL;
if (!dir_emit_dots(file, ctx))
return 0;
/*
- * One buffer for the call, holding the name of the entry the listing
- * is on. PATH_MAX: kernfs bounds no single name.
+ * Two buffers: the name of the entry found, and the name of the entry
+ * before it, which is where the search resumes. PATH_MAX: kernfs
+ * bounds no single name.
*/
- name = kmalloc(PATH_MAX, GFP_KERNEL);
- if (!name)
+ buf1 = kmalloc(PATH_MAX, GFP_KERNEL);
+ buf2 = kmalloc(PATH_MAX, GFP_KERNEL);
+ if (!buf1 || !buf2)
return -ENOMEM;
+ name = buf1;
- root = kernfs_root(parent);
- down_read(&root->kernfs_rwsem);
-
- if (kernfs_ns_enabled(parent))
+ /*
+ * KERNFS_NS is set before @parent has children and never cleared. The
+ * other bits in the word can change under us, as in
+ * kernfs_dop_revalidate().
+ */
+ if (data_race(kernfs_ns_enabled(parent)))
ns = kernfs_info(dentry->d_sb)->ns;
- for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos, NULL, NULL);
- pos;
- pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos, name)) {
- unsigned int type = fs_umode_to_dtype(pos->mode);
- ino_t ino = kernfs_ino(pos);
- int len;
+ /* the cursor's reference belongs to this call now */
+ file->private_data = NULL;
+
+ while (ctx->pos < INT_MAX) {
+ unsigned int pos_hash = 0, type = 0, seq;
+ struct kernfs_node *pos;
+ ino_t ino = 0;
+ bool pinned;
+ int len = 0, tries;
/*
- * The copy is also the resume key, so a truncated name would
- * resume here again. getname() caps a path, so only an
- * in-kernel caller can get here; end the listing instead.
+ * Find the entry and copy everything that is listed or resumed
+ * from in one read section, so that a rename in between cannot
+ * make the listing skip or repeat entries. If the directory
+ * keeps changing, stop it with kernfs_rwsem, so that the listing
+ * makes progress.
*/
- len = strscpy(name, kernfs_rcu_name(pos), PATH_MAX);
- if (WARN_ON_ONCE(len < 0))
- break;
+ rcu_read_lock();
+ for (tries = 0; ; tries++) {
+ if (tries == KERNFS_READDIR_TRIES) {
+ rcu_read_unlock();
+ down_read(&parent->dir.root->kernfs_rwsem);
+ rcu_read_lock();
+ }
+ seq = read_seqcount_begin(&parent->dir.seq);
+ if (cursor &&
+ kernfs_dir_cursor_valid(parent, cursor, ns, ctx->pos))
+ pos = cursor;
+ else if (key)
+ pos = kernfs_dir_visible_after(parent, ns, key_hash,
+ key, seq);
+ else
+ pos = kernfs_dir_visible_after(parent, ns, ctx->pos,
+ "", seq);
+ if (pos) {
+ len = strscpy(name, kernfs_rcu_name(pos), PATH_MAX);
+ ino = kernfs_ino(pos);
+ type = fs_umode_to_dtype(READ_ONCE(pos->mode));
+ pos_hash = READ_ONCE(pos->hash);
+ }
+ if (!read_seqcount_retry(&parent->dir.seq, seq))
+ break;
+ }
- ctx->pos = pos->hash;
- file->private_data = pos;
- kernfs_get(pos);
+ /* a node whose count is zero is unlinked and being freed */
+ pinned = pos && (pos == cursor || atomic_inc_not_zero(&pos->count));
+ rcu_read_unlock();
+ if (tries >= KERNFS_READDIR_TRIES)
+ up_read(&parent->dir.root->kernfs_rwsem);
+
+ /* the cursor's reference is now @pos's, or no longer needed */
+ if (cursor && pos != cursor)
+ kernfs_put(cursor);
+ cursor = NULL;
+ if (!pos)
+ break;
/*
- * dir_emit() can fault, so run it unlocked. @pos is pinned
- * above and kernfs_dir_pos() rechecks it on the way back.
+ * The name is also where the next search resumes, so a truncated
+ * one would resume here again. getname() caps a path, so only an
+ * in-kernel caller can get here; end the listing instead.
*/
- up_read(&root->kernfs_rwsem);
- if (!dir_emit(ctx, name, len, ino, type))
+ if (WARN_ON_ONCE(len < 0)) {
+ if (pinned)
+ kernfs_put(pos);
+ break;
+ }
+
+ /* resume after @pos, whose name is in @name */
+ key = name;
+ key_hash = pos_hash;
+ name = name == buf1 ? buf2 : buf1;
+
+ /* @pos was removed meanwhile: go on after it */
+ if (!pinned)
+ continue;
+
+ /* dir_emit() can fault, so run it unlocked; @pos is pinned */
+ ctx->pos = pos_hash;
+ file->private_data = pos;
+ if (!dir_emit(ctx, key, len, ino, type))
return 0;
- down_read(&root->kernfs_rwsem);
+ file->private_data = NULL;
+ kernfs_put(pos);
}
- up_read(&root->kernfs_rwsem);
- file->private_data = NULL;
+ /* the loop did not run if the position was already past the end */
+ kernfs_put(cursor);
ctx->pos = INT_MAX;
return 0;
}
--
2.53.1-Meta
prev parent reply other threads:[~2026-12-04 21:11 UTC|newest]
Thread overview: 4+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-04 21:10 [PATCH 0/3] kernfs: list directories without kernfs_rwsem Shakeel Butt
2026-12-04 21:10 ` [PATCH 1/3] kernfs: don't look for open files of directories when draining Shakeel Butt
2026-12-04 21:10 ` [PATCH 2/3] kernfs: add a sequence count to directories Shakeel Butt
2026-12-04 21:10 ` Shakeel Butt [this message]
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261204211034.3436390-4-shakeel.butt@linux.dev \
--to=shakeel.butt@linux.dev \
--cc=akpm@linux-foundation.org \
--cc=brauner@kernel.org \
--cc=cgroups@vger.kernel.org \
--cc=driver-core@lists.linux.dev \
--cc=gregkh@linuxfoundation.org \
--cc=jkoolstra@xs4all.nl \
--cc=kernel-team@meta.com \
--cc=linux-fsdevel@vger.kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=raven@themaw.net \
--cc=tj@kernel.org \
--cc=tjmercier@google.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox