From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=95.215.58.236 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796418667; b=W7Y3hlhZryEN18r9y/NVpXExDmwsqahGUXsvSx1TrGqgjfhwD4SYIrKle0W1XIYsSKpB UaEZnsdli6xpHyPgfwmTXP49pl1fI6Y+hrKW3vacbxXBVli3hwilj5BA6zr/iir/gg7tX 36Hettcchnqc+RNOXkRMV9oMQj/wIqumu1a6nL5R+gs773MPxJWzqIhMc/e1azd0ltqMb ft5CU4SZbMWsbABlz4aV5O5plPC6RIbqpl4/wqUQBnnUmDqYcFHrRSjXmNZBKd71595QS bV8k2pPzIHV7AcPCAqQ36kqje/dt568b9uphzN0tCOIxGU+KweEugEyxf8HiZcmRn/g== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796418667; h=DMARC-Filter:X-Envelope-To:DKIM-Signature:X-Envelope-To:Received: X-Mizu-Trace-ID:X-Migadu-Flow:From:To:Cc:Subject:Date:Message-ID: X-Mailer:In-Reply-To:References:MIME-Version: Content-Transfer-Encoding; bh=z/9xlf+FuXYzyVwRSPA6XDWrN3BKi9hqOPEkwZqF2QA=; b=bqVdeKs/NPQhUG9Agnxr2+XDhl4ldZweI2JzBS4M1j/r9ljZQEEY2FurMfYuzyaipwzE bfT+bvauS/wQKJsxqiOwGR+76UO+5lIjg6b4G4fRNoIu0idKh7wn4anN/+yhg2Qr1g1V4 DQG2tZnqR72vjDC7q9s0CIJAzoNSFrZhHOVGUE9hEtWsArWAfP/p6oziz+nKk/ITCRebq xRSPiZO4hpjVQ6gsCdU36QPMRJ91IRzFM7QbVe1ZFQY8EpHquldkYpEeDJfCBSrAl35As gHskdL02fvQOrz+rBwKRruZGbvNoW8dn+LywK9zU3yH+E4VQX+TE7tCvg23TXZctwhw== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=linux.dev; spf=pass smtp.mailfrom=linux.dev; dkim=pass header.d=linux.dev header.i=@linux.dev header.a=rsa-sha256 header.s=key1 header.b=hoRGF8k+; arc=none smtp.remote-ip=95.215.58.236 Received: from mta1.migadu.com (out-236.mta1.migadu.com [95.215.58.236]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F3ED2606A333 for ; Fri, 4 Dec 2026 21:11:06 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F3ED2606A333 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=linux.dev Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=linux.dev Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key, unprotected) header.d=linux.dev header.i=@linux.dev header.a=rsa-sha256 header.s=key1 header.b=hoRGF8k+ X-Envelope-To: cgroups@vger.kernel.org DKIM-Signature: a=rsa-sha256; bh=tE7I1RJx8AUcVglYG3fXM0+2CKga9rDIHo6OoV7iDOc=; c=simple/simple; d=linux.dev; h=from:to:subject:date:message-id:mime-version:content-type; s=key1; t=1796418665; v=1; x=1797023465; b=hoRGF8k+e5boJNEZ0ZrjTqw7WtKCXjLkVOmldn1XCLeVRXXtEeCX/XLdA2FQu0fwoqvwj9LD C57yD3PuBh8xW9G162fjsSaxbLpAt7558lqLbZJ6yogzz5x6T4kJOpqSf7m9XzlaHdkHpV9AWdU AdpMnTs2KMvDHx5BhSj0W0CU= X-Envelope-To: cgroups@vger.kernel.org Received: by smtp.migadu.com with ESMTPS id 82a358d661c3695a; Fri, 04 Dec 2026 21:11:02 +0000 X-Mizu-Trace-ID: 82a358d661c3695a X-Migadu-Flow: FLOW_OUT From: Shakeel Butt To: Christian Brauner Cc: Greg Kroah-Hartman , Tejun Heo , Andrew Morton , Ian Kent , Jori Koolstra , "T . J . Mercier" , Meta kernel team , 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 Message-ID: <20261204211034.3436390-4-shakeel.butt@linux.dev> X-Mailer: git-send-email 2.53.1 In-Reply-To: <20261204211034.3436390-1-shakeel.butt@linux.dev> References: <20261204211034.3436390-1-shakeel.butt@linux.dev> X-Mailing-List: cgroups@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit 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 --- 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