Skip to contentSkip to conversation

kernfs, driver core: Cut per-node lock traffic in bulk registration

PATCH In review Pavol Sakac 2 participants 6 messages Sep 11

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

cover kernfs, driver core: Cut per-node lock traffic in bulk registration

Registering VFs in parallel, introduced in [1], runs into three lock costs in kernfs and the driver core. Two scale with the number of sysfs nodes created: the kernfs root rwsem is write-taken twice per node, and every inode ID is allocated under kernfs_idr_lock. The third scales with the number of devices: get_device_parent()'s glue directory lookup walks a flat list under the global gdp_mutex.

The glue directory is how the driver core groups class devices under a parent that is not itself a class device: when vfio-pci binds, each VF gets a "vfio-dev" glue directory holding its vfio-dev class device. get_device_parent() finds or creates it by walking the class's flat glue_dirs list under gdp_mutex, so with thousands of VFs each registration walks thousands of entries - quadratic work, serialized on one global mutex.

Patch 1 (kernfs) activates a new node inside the same kernfs_rwsem write hold that links it: one write acquisition per node instead of two. Patch 2 (driver core) indexes glue directories by parent kobject in an rbtree, replacing the linear walk; gdp_mutex still serializes as before. Patch 3 (kernfs) pre-allocates inode IDs in batches of 16, caches them per CPU, and installs the node pointer with an RCU store via idr_replace(), cutting kernfs_idr_lock acquisitions 16x.

Lock statistics and SR-IOV init time for 4x PF (NVMe, 255 VFs each), on the reproducer from the parallel VF initialization cover letter [1]:

lock_stat:
Lock wait: Before After contentions: Before After

  iommu_probe_device_lock      10471 ms   9154 ms                   841     783
  &vfio.group_lock              3614 ms   3823 ms                   736     730
  &root->kernfs_rwsem           1834 ms   1285 ms                116316   55459

&root->kernfs_idr_lock 5 ms 0 ms 4580 77

iommu_probe_device_lock and vfio.group_lock are shown for scale; neither is touched by this series - they are addressed by the IOMMU [2] and VFIO [3] series posted separately.

  kernfs_rwsem write acquisitions  168302 (2/node) -> 84661 (1/node)
  kernfs_idr_lock acquisitions     83641 -> 5229 (batch 16)
  gdp_mutex avg hold               18 -> 7 us (2040 acq. both arms)

Stage SR-IOV init time:
S0 (baseline) 3027 ms

  S1                     999 ms
  S2                     995 ms
  S3 (this series)       991 ms

Reproducer disclaimer:
I lean primarily on lock_stat numbers to defend the improvements. In the reproducer, the residual iommu_probe_device_lock dominates the window and masks the later series' wall-time gains; reducing that lock further is out of scope for this set. On real hardware the five series together cut SR-IOV initialization by 65%, more in [1].

The staged sysfs RFC [4] builds on top of these changes (mainly the IDR batching).

This series adds a KUnit suite. The lock_stat and timing figures come from the public reproducer. The full series has also been tested on current datacenter server hardware with thousands of VFs.

[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]
[3] https://lore.kernel.org/r/[email protected]
[4] https://lore.kernel.org/r/[email protected]

Pavol Sakac (3):
kernfs: activate nodes while linking them
driver core: Index class glue directories by parent kobject
kernfs: batch inode ID allocation per CPU

 drivers/base/base.h                  |   4 +
 drivers/base/core.c                  | 112 +++++--
 drivers/base/test/.kunitconfig       |   1 +
 drivers/base/test/Kconfig            |  12 +
 drivers/base/test/Makefile           |   2 +
 drivers/base/test/glue-dir-test.c    | 466 +++++++++++++++++++++++++++
 drivers/base/test/root-device-test.c | 215 ++++++++++++
 fs/kernfs/dir.c                      | 139 +++++++-
 fs/kernfs/kernfs-internal.h          |   3 +
 fs/sysfs/mount.c                     |   3 +-
 include/linux/kernfs.h               |  13 +
 11 files changed, 930 insertions(+), 40 deletions(-)
 create mode 100644 drivers/base/test/glue-dir-test.c

base-commit: cee9395acd8043be0644b25c34bfa86623f2b935

Signature · 1 line
2.47.3
#1 lore raw

PATCH 1/3 kernfs: activate nodes while linking them

kernfs_add_one() links a new node, releases kernfs_rwsem, and takes it again through kernfs_activate(). A new node has no descendants, so the second hold only activates that node.

Activate ordinary nodes before releasing the linking hold, removing a second write-side acquisition and the linked-but-inactive interval. KERNFS_ROOT_CREATE_DEACTIVATED roots retain explicit subtree activation.

Removing the unlock-to-lock pair also removes its publication ordering. The in-tree lockless ID lookups use CREATE_DEACTIVATED roots and retain kernfs_activate(); unsynchronized callers cannot rely on observing a node.

Assisted-by LLM
---
 fs/kernfs/dir.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
fs/kernfs/dir.c +9 -8
index 82bbaeb326aa..d68bce0b0b41 100644
@@ -41,6 +41,8 @@ static bool kernfs_active(struct kernfs_node *kn)
 	return __kernfs_active(kn);
 }
 
+static void kernfs_activate_one(struct kernfs_node *kn);
+
 static bool kernfs_lockdep(struct kernfs_node *kn)
 {
 #ifdef CONFIG_DEBUG_LOCK_ALLOC
@@ -855,17 +857,16 @@ int kernfs_add_one(struct kernfs_node *kn)
 	}
 
 	up_write(&root->kernfs_iattr_rwsem);
-	up_write(&root->kernfs_rwsem);
 
 	/*
-	 * Activate the new node unless CREATE_DEACTIVATED is requested.
-	 * If not activated here, the kernfs user is responsible for
-	 * activating the node with kernfs_activate().  A node which hasn't
-	 * been activated is not visible to userland and its removal won't
-	 * trigger deactivation.
+	 * A freshly linked node has no descendants, so activating just @kn
+	 * under the linking hold is equivalent to the kernfs_activate()
+	 * walk; CREATE_DEACTIVATED roots keep deferred activation.
 	 */
-	if (!(kernfs_root(kn)->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
-		kernfs_activate(kn);
+	if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED))
+		kernfs_activate_one(kn);
+
+	up_write(&root->kernfs_rwsem);
 	return 0;
 
 out_unlock:
Signature · 1 line
2.47.3
#2 lore raw

Re: [PATCH 1/3] kernfs: activate nodes while linking them

Quoted 12 lines · Pavol Sakac

kernfs_add_one() links a new node, releases kernfs_rwsem, and takes it again through kernfs_activate(). A new node has no descendants, so the second hold only activates that node.

Activate ordinary nodes before releasing the linking hold, removing a second write-side acquisition and the linked-but-inactive interval. KERNFS_ROOT_CREATE_DEACTIVATED roots retain explicit subtree activation.

Removing the unlock-to-lock pair also removes its publication ordering. The in-tree lockless ID lookups use CREATE_DEACTIVATED roots and retain kernfs_activate(); unsynchronized callers cannot rely on observing a node.

...

fs/kernfs/dir.c static bool kernfs_active(struct kernfs_node *kn) · line 45

Quoted 2 lines
fs/kernfs/dir.c +2 -0
+static void kernfs_activate_one(struct kernfs_node *kn);
+

Can we avoid adding forward declarations like this? Or is there circular dependencies? If not, add another patch that simply moves the existing code upper, so this patch won't need a forward declaration.

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#3 lore raw

PATCH 2/3 driver core: Index class glue directories by parent kobject

In reply to Pavol Sakac

get_device_parent() finds a parent's glue directory by walking the class's glue_dirs kset list under gdp_mutex, so one per parent, as vfio-dev needs per SR-IOV VF, is quadratic.

Index them by parent kobject in an rbtree embedded in the class's subsys_private, which dies with the kset list it indexes, so no per-entry class check is needed: two classes below one parent are told apart by tree selection. The key is a kobject because a parentless class device hangs off the shared "virtual" kobject, referenced by the glue dir while indexed. The rb_node lives in struct class_dir, adding no allocation and no failure mode.

gdp_mutex serializes the index, as it has glue dir lookup/create/remove since commit 77d3d7c1d561f
("driver-core: fix race condition in get_device_parent()") and commit e4a60d1390609
("sysfs: driver core: Fix glue dir race condition by gdp_mutex").

A kernfs name lookup in the parent's directory needs no new state, but takes the kernfs root rwsem under gdp_mutex, behind the writes concurrent sysfs directory creation generates.

A KUnit suite covers the index: reuse of one parent's glue directory, two classes below one parent, the parentless "virtual" cases, reap and recreate, name collision, many parents, device_move(), and class teardown.

Assisted-by LLM
---
 drivers/base/base.h               |   4 +
 drivers/base/core.c               | 112 +++++--
 drivers/base/test/.kunitconfig    |   1 +
 drivers/base/test/Kconfig         |  12 +
 drivers/base/test/Makefile        |   2 +
 drivers/base/test/glue-dir-test.c | 466 ++++++++++++++++++++++++++++++
 6 files changed, 566 insertions(+), 31 deletions(-)
 create mode 100644 drivers/base/test/glue-dir-test.c
drivers/base/base.h +4 -0
index a5b7abc10ff0..f5d608f4aaa5 100644
@@ -11,6 +11,7 @@
  *
  */
 #include <linux/notifier.h>
+#include <linux/rbtree_types.h>
 
 /**
  * struct subsys_private - structure to hold the private to the driver core
@@ -32,6 +33,8 @@
  * @dev_root: Default device to use as the parent.
  * @glue_dirs: "glue" directory to put in-between the parent device to
  *	       avoid namespace conflicts
+ * @glue_dirs_index: the class's glue dirs by parent kobject, under gdp_mutex;
+ *		     zeroed is an empty rb_root
  * @class: pointer back to the struct class that this structure is associated
  *	   with.
  * @lock_key: Lock class key for use by the lock validator
@@ -55,6 +58,7 @@ struct subsys_private {
 	struct device *dev_root;
 
 	struct kset glue_dirs;
+	struct rb_root glue_dirs_index;
 	const struct class *class;
 
 	struct lock_class_key lock_key;
drivers/base/core.c +81 -31

173 lines not on this page · raw message

drivers/base/test/.kunitconfig +1 -0
index 473923f0998b..28322bad39a7 100644
@@ -1,2 +1,3 @@
 CONFIG_KUNIT=y
 CONFIG_DM_KUNIT_TEST=y
+CONFIG_GLUE_DIR_KUNIT_TEST=y
drivers/base/test/Kconfig +12 -0
index 542ce07530a1..253b5bd96aff 100644
@@ -24,3 +24,15 @@ config DRIVER_SWNODE_KUNIT_TEST
 	tristate "KUnit Tests for software node fw_devlink links" if !KUNIT_ALL_TESTS
 	depends on KUNIT
 	default KUNIT_ALL_TESTS
+
+config GLUE_DIR_KUNIT_TEST
+	tristate "KUnit Tests for class glue directories" if !KUNIT_ALL_TESTS
+	depends on KUNIT && SYSFS
+	default KUNIT_ALL_TESTS
+	help
+	  Enable this option to test the class glue directories the driver
+	  core places class devices under: that siblings share one, that a
+	  reaped one is created again, and that a same-named child which is
+	  not a glue directory is never mistaken for one.
+
+	  If unsure say N.
drivers/base/test/Makefile +2 -0
index 9ced7bbd569f..f13f0c399bea 100644
@@ -8,3 +8,5 @@ obj-$(CONFIG_DRIVER_PE_KUNIT_TEST) += property-entry-test.o
 CFLAGS_property-entry-test.o += $(DISABLE_STRUCTLEAK_PLUGIN)
 
 obj-$(CONFIG_DRIVER_SWNODE_KUNIT_TEST) += swnode-devlink-test.o
+
+obj-$(CONFIG_GLUE_DIR_KUNIT_TEST) += glue-dir-test.o
drivers/base/test/glue-dir-test.c new file +466 -0

466 lines not on this page · raw message

Signature · 1 line
2.47.3
#4 lore raw

Re: [PATCH 2/3] driver core: Index class glue directories by parent kobject

Quoted 26 lines · Pavol Sakac

get_device_parent() finds a parent's glue directory by walking the class's glue_dirs kset list under gdp_mutex, so one per parent, as vfio-dev needs per SR-IOV VF, is quadratic.

Index them by parent kobject in an rbtree embedded in the class's subsys_private, which dies with the kset list it indexes, so no per-entry class check is needed: two classes below one parent are told apart by tree selection. The key is a kobject because a parentless class device hangs off the shared "virtual" kobject, referenced by the glue dir while indexed. The rb_node lives in struct class_dir, adding no allocation and no failure mode.

gdp_mutex serializes the index, as it has glue dir lookup/create/remove since commit 77d3d7c1d561f
("driver-core: fix race condition in get_device_parent()") and commit e4a60d1390609
("sysfs: driver core: Fix glue dir race condition by gdp_mutex").

A kernfs name lookup in the parent's directory needs no new state, but takes the kernfs root rwsem under gdp_mutex, behind the writes concurrent sysfs directory creation generates.

A KUnit suite covers the index: reuse of one parent's glue directory, two classes below one parent, the parentless "virtual" cases, reap and recreate, name collision, many parents, device_move(), and class teardown.

...

drivers/base/test/.kunitconfig line 3

Quoted 5 lines

+++ b/drivers/base/test/.kunitconfig

drivers/base/test/.kunitconfig +1 -0
@@ -1,2 +1,3 @@
 CONFIG_KUNIT=y
 CONFIG_DM_KUNIT_TEST=y
+CONFIG_GLUE_DIR_KUNIT_TEST=y

Is this test case is so important that it must *always* run?

Signature · 2 lines
With Best Regards,
Andy Shevchenko
#5 lore raw

PATCH 3/3 kernfs: batch inode ID allocation per CPU

In reply to Pavol Sakac

Every kernfs node allocates an inode ID from its root's IDR under the per-root kernfs_idr_lock (per-root since commit cec59c440a05c ("kernfs:
switch global kernfs_idr_lock to per-fs lock")). sysfs is a single root, so parallel creation funnels every node through one lock, and a registration storm acquires it once per created node: even registrations in disjoint subtrees contend on that one spinlock.

Let opted-in roots reserve a batch of IDs as NULL IDR entries and cache them per CPU, so node creation pops one and installs itself with idr_replace() under rcu_read_lock() instead of taking the shared lock.

Each call stays within the documented IDR contract: idr_replace() may run under the RCU read lock concurrently with the idr_alloc() and idr_remove() other CPUs do under the lock, and installing into an entry reserved as NULL is the reserve-then-replace pattern of Documentation/core-api/idr.rst. The property relied on beyond that is concurrent idr_replace() on distinct reserved IDs, the normal mode here since each reserved ID goes to exactly one caller; it holds because replacing a reserved slot (NULL, IDR_FREE clear) is a single rcu_assign_pointer() store and nothing else, and calculate_count() returns 0 for such a slot, so the transition is count-neutral, writes no shared radix-tree state, and cannot interact with a concurrent replace of a distinct slot even within one radix-tree node.

Refill failure falls back to the locked path. An opted-in root must not also ask for KERNFS_ROOT_SUPPORT_EXPORTOP, whose fhandle by-id lookups must not meet an ino that is allocated but owned by no node. Enable batching for sysfs: with batching, a registration storm takes kernfs_idr_lock once per KERNFS_INO_BATCH-sized batch of nodes instead of once per node.

Add root_device_ino_uniqueness_test to the root-device-devm KUnit
suite: it registers devices from several tasks at once, each crossing a batch refill, and requires the IDs of nodes that are all alive at the same time to be distinct.

Assisted-by LLM
---
 drivers/base/test/root-device-test.c | 215 +++++++++++++++++++++++++++
 fs/kernfs/dir.c                      | 122 +++++++++++++++
 fs/kernfs/kernfs-internal.h          |   3 +
 fs/sysfs/mount.c                     |   3 +-
 include/linux/kernfs.h               |  13 ++
 5 files changed, 355 insertions(+), 1 deletion(-)
drivers/base/test/root-device-test.c +215 -0
index 9aea23c9123e..f3370d53f9d4 100644
@@ -3,7 +3,12 @@
 
 #include <kunit/resource.h>
 
+#include <linux/completion.h>
+#include <linux/cpumask.h>
 #include <linux/device.h>
+#include <linux/kernfs.h>
+#include <linux/kthread.h>
+#include <linux/sort.h>
 
 #define DEVICE_NAME "test"
 
@@ -93,9 +98,219 @@ static void root_device_devm_register_get_unregister_with_devm_test(struct kunit
 	KUNIT_EXPECT_GT(test, ret, 0);
 }
 
+#if IS_ENABLED(CONFIG_SYSFS)
+/*
+ * Inode IDs may be handed out from per-CPU batches (KERNFS_ROOT_INO_BATCH on
+ * the sysfs root); one task's loop only draws from the CPU it runs on and
+ * would pass unchanged if batching were inert.  Hence several tasks at
+ * once.  Per task: more than INO_BATCH IDs for every online CPU, so a
+ * refill is crossed even if a task migrates across all of them, and never
+ * a whole number of batches, so the run also ends mid-batch.
+ */
+#define INO_THREADS		4
+#define INO_BATCH		16	/* KERNFS_INO_BATCH (kernfs-private) */
+#define INO_MIN_PER_THREAD	200
+/* one worker's registrations scale with the CPU count: ~0.5ms each on 4 CPUs */
+#define INO_TIMEOUT_BASE_MS	5000
+#define INO_TIMEOUT_PER_DEV_MS	10
+
+struct ino_worker {
+	int idx;
+	int nr;				/* devices to register */
+	int created;			/* devices actually registered */
+	int err;			/* first registration error */
+	bool joined;			/* completion was waited out */
+	struct device **devs;
+	ino_t *inos;
+	struct completion done;
+};
+
+struct ino_test_ctx {
+	struct ino_worker worker[INO_THREADS];
+	int spawned;
+};
+
+static int root_device_ino_worker(void *data)
+{
+	struct ino_worker *w = data;
+	int i;
+
+	for (i = 0; i < w->nr; i++) {
+		char name[32];
+		struct device *dev;
+
+		snprintf(name, sizeof(name), DEVICE_NAME "-ino-%d-%d",
+			 w->idx, i);
+		dev = root_device_register(name);
+		if (IS_ERR(dev)) {
+			w->err = PTR_ERR(dev);
+			break;
+		}
+		w->devs[i] = dev;
+		w->inos[i] = dev->kobj.sd ? kernfs_ino(dev->kobj.sd) : 0;
+		w->created = i + 1;
+	}
+
+	/*
+	 * complete_all(), not complete(): this is waited on twice, once by
+	 * the test and once by the teardown action, and a plain completion
+	 * is consumed by the first waiter.
+	 */
+	complete_all(&w->done);
+	return 0;
+}
+
+/*
+ * Registered before the first worker is spawned, so it also runs if the test
+ * aborts: join every worker, then undo what it did.
+ */
+static void root_device_ino_teardown(void *data)
+{
+	struct ino_test_ctx *ctx = data;
+	int t, i;
+
+	for (t = 0; t < ctx->spawned; t++)
+		wait_for_completion(&ctx->worker[t].done);
+
+	for (t = 0; t < INO_THREADS; t++)
+		for (i = 0; i < ctx->worker[t].created; i++)
+			root_device_unregister(ctx->worker[t].devs[i]);
+}
+
+static int ino_cmp(const void *a, const void *b)
+{
+	ino_t x = *(const ino_t *)a;
+	ino_t y = *(const ino_t *)b;
+
+	if (x < y)
+		return -1;
+	return x > y;
+}
+
+static void root_device_ino_uniqueness_test(struct kunit *test)
+{
+	int zeros = 0, dups = 0, descents = 0, ids = 0;
+	struct ino_test_ctx *ctx;
+	bool results_valid = true;
+	unsigned long timeout;
+	struct device **devs;
+	ino_t *inos, *sorted;
+	int nr, total, t, i;
+
+	nr = INO_BATCH * num_online_cpus() + INO_BATCH / 2;
+	if (nr < INO_MIN_PER_THREAD)
+		nr = INO_MIN_PER_THREAD;
+	total = INO_THREADS * nr;
+	timeout = msecs_to_jiffies(INO_TIMEOUT_BASE_MS +
+				   nr * INO_TIMEOUT_PER_DEV_MS);
+
+	ctx = kunit_kzalloc(test, sizeof(*ctx), GFP_KERNEL);
+	devs = kunit_kcalloc(test, total, sizeof(*devs), GFP_KERNEL);
+	inos = kunit_kcalloc(test, total, sizeof(*inos), GFP_KERNEL);
+	sorted = kunit_kcalloc(test, total, sizeof(*sorted), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ctx);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, devs);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, inos);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, sorted);
+
+	for (t = 0; t < INO_THREADS; t++) {
+		struct ino_worker *w = &ctx->worker[t];
+
+		w->idx = t;
+		w->nr = nr;
+		w->devs = devs + t * nr;
+		w->inos = inos + t * nr;
+		init_completion(&w->done);
+	}
+
+	KUNIT_ASSERT_EQ(test,
+			kunit_add_action_or_reset(test,
+						  root_device_ino_teardown,
+						  ctx), 0);
+
+	for (t = 0; t < INO_THREADS; t++) {
+		struct task_struct *task;
+
+		task = kthread_run(root_device_ino_worker, &ctx->worker[t],
+				   "root_dev_ino%d", t);
+		if (IS_ERR(task))
+			break;
+		ctx->spawned++;
+	}
+	KUNIT_EXPECT_EQ(test, ctx->spawned, INO_THREADS);
+	if (ctx->spawned != INO_THREADS)
+		results_valid = false;
+
+	/*
+	 * complete_all() is a worker's last act, so only a join that succeeds
+	 * orders its stores before the reads below; a worker that timed out
+	 * may still be writing its slice.  The teardown action joins those
+	 * unbounded, before any of this memory can be freed.
+	 */
+	for (t = 0; t < ctx->spawned; t++) {
+		struct ino_worker *w = &ctx->worker[t];
+
+		if (wait_for_completion_timeout(&w->done, timeout) > 0) {
+			w->joined = true;
+		} else {
+			KUNIT_FAIL(test, "worker %d timed out", t);
+			results_valid = false;
+		}
+	}
+
+	for (t = 0; t < ctx->spawned; t++) {
+		struct ino_worker *w = &ctx->worker[t];
+
+		if (!w->joined)
+			continue;
+
+		KUNIT_EXPECT_EQ(test, w->err, 0);
+		KUNIT_EXPECT_EQ(test, w->created, nr);
+		if (w->err || w->created != nr)
+			results_valid = false;
+
+		for (i = 0; i < w->created; i++) {
+			if (!w->inos[i])
+				zeros++;
+			/*
+			 * Batches are consumed from the top: IDs step down
+			 * within one, while the locked path only ascends, so
+			 * one descent is evidence the cache was in use.
+			 */
+			if (i && w->inos[i] < w->inos[i - 1])
+				descents++;
+			sorted[ids++] = w->inos[i];
+		}
+	}
+	KUNIT_EXPECT_EQ(test, zeros, 0);
+
+	/* every ID belongs to a node that is still alive here */
+	sort(sorted, ids, sizeof(*sorted), ino_cmp, NULL);
+	for (i = 1; i < ids; i++)
+		if (sorted[i] == sorted[i - 1])
+			dups++;
+	KUNIT_EXPECT_EQ(test, dups, 0);
+	if (zeros || dups)
+		results_valid = false;
+
+	/*
+	 * The batch cache is best-effort: when its allocation failed, every
+	 * ID above came from the locked fallback and no descent can have been
+	 * observed.  Make that visibly unavailable coverage rather than a
+	 * PASS that never exercised batching -- but only when everything
+	 * above held, since kunit_skip() would overwrite a recorded failure.
+	 */
+	if (IS_ENABLED(CONFIG_SMP) && results_valid && !descents)
+		kunit_skip(test, "sysfs inode batching fast path was not observed");
+}
+#endif
+
 static struct kunit_case root_device_devm_tests[] = {
 	KUNIT_CASE(root_device_devm_register_unregister_test),
 	KUNIT_CASE(root_device_devm_register_get_unregister_with_devm_test),
+#if IS_ENABLED(CONFIG_SYSFS)
+	KUNIT_CASE(root_device_ino_uniqueness_test),
+#endif
 	{}
 };
 
fs/kernfs/dir.c +122 -0

158 lines not on this page · raw message

fs/kernfs/kernfs-internal.h +3 -0
index aa784b540b36..6e12233731e6 100644
@@ -30,6 +30,8 @@ struct kernfs_iattrs {
 	struct simple_xattr_limits xattr_limits;
 };
 
+struct kernfs_ino_cache;
+
 struct kernfs_root {
 	/* published fields */
 	struct kernfs_node	*kn;
@@ -40,6 +42,7 @@ struct kernfs_root {
 	spinlock_t		kernfs_idr_lock;	/* root->ino_idr */
 	u32			last_id_lowbits;
 	u32			id_highbits;
+	struct kernfs_ino_cache __percpu *ino_cache;
 	struct kernfs_syscall_ops *syscall_ops;
 
 	/* list of kernfs_super_info of this root, protected by kernfs_rwsem */
fs/sysfs/mount.c +2 -1
index 88c10823fcaf..86288c5e34e8 100644
@@ -86,7 +86,8 @@ int __init sysfs_init(void)
 {
 	int err;
 
-	sysfs_root = kernfs_create_root(NULL, KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK,
+	sysfs_root = kernfs_create_root(NULL, KERNFS_ROOT_EXTRA_OPEN_PERM_CHECK |
+					KERNFS_ROOT_INO_BATCH,
 					NULL);
 	if (IS_ERR(sysfs_root))
 		return PTR_ERR(sysfs_root);
include/linux/kernfs.h +13 -0
index 351a5101c862..6440882b7d58 100644
@@ -156,6 +156,19 @@ enum kernfs_root_flag {
 	 * Renames must not change the parent node.
 	 */
 	KERNFS_ROOT_INVARIANT_PARENT		= 0x0010,
+
+	/*
+	 * Reserve inode numbers for this root in per-CPU batches, taking the
+	 * root's ID allocation lock out of the per-node creation path.
+	 * Best-effort: if the cache cannot be allocated the root falls back to
+	 * the locked path.  Costs up to KERNFS_INO_BATCH - 1
+	 * reserved-but-unused IDs per possible CPU per opted-in root, held as
+	 * NULL IDR entries until the root's IDR is destroyed.  Must not be
+	 * combined with KERNFS_ROOT_SUPPORT_EXPORTOP: reserved IDs are
+	 * allocated inos with no node, which the fhandle by-id lookup must not
+	 * resolve.
+	 */
+	KERNFS_ROOT_INO_BATCH			= 0x0020,
 };
 
 /* type-specific structures for kernfs_node union members */
Signature · 1 line
2.47.3