Skip to contentSkip to conversation

spi: add new_device/delete_device sysfs interface

PATCH Superseded Vishwaroop A 2 participants 8 messages May 17 – Jul 27

Subsystems (3)

v5 of 9 Superseded Latest is v9 →

lore
Share & tools
lore
#0 lore raw

v5 cover spi: add new_device/delete_device sysfs interface

Add I2C-style new_device/delete_device sysfs attributes to SPI host controllers, allowing userspace to instantiate and remove SPI devices at runtime without device-tree changes.

Changes since v4:
- Removed spi_unregister_device() call from new_device_store()'s ctlr->dead teardown path. That call raced with device_for_each_child(__unregister) in spi_unregister_controller(), causing a double-free. The extra get_device() ref keeps the struct alive; __unregister handles the actual cleanup.

Changes since v3:
- Replaced holding add_lock across __spi_add_device() + list insertion (which caused an ABBA deadlock between add_lock and the kernfs active reference during concurrent unbind) with:
* A 'dead' flag on spi_controller, set in spi_unregister_controller() under both add_lock and userspace_clients_lock.
* __spi_add_device() checks ctlr->dead under add_lock to reject new devices after teardown begins.
* new_device_store() checks ctlr->dead under userspace_clients_lock before list insertion, falling back to cleanup + ENODEV.
* add_lock is released before device_del() so in-flight sysfs stores can drain without deadlocking.
* get_device() taken before spi_add_device() prevents use-after-free if __unregister runs concurrently.
- Used #if IS_ENABLED() preprocessor guard (not runtime IS_ENABLED()) for the ctlr->dead check in __spi_add_device(), since the dead field is conditionally compiled.

Changes since v2:
- Gated sysfs attributes and locking on CONFIG_SPI_DYNAMIC.

Changes since v1:
- Added locking to prevent races between new_device_store() and concurrent spi_unregister_controller().

Vishwaroop A (2):
spi: add new_device/delete_device sysfs interface
docs: spi: add documentation for userspace device instantiation

 .../ABI/testing/sysfs-class-spi-master        |  34 +++
 Documentation/spi/index.rst                   |   1 +
 Documentation/spi/instantiating-devices.rst   |  88 +++++++
 drivers/spi/spi.c                             | 217 +++++++++++++++++-
 include/linux/spi/spi.h                       |  13 ++
 5 files changed, 347 insertions(+), 6 deletions(-)
 create mode 100644 Documentation/ABI/testing/sysfs-class-spi-master
 create mode 100644 Documentation/spi/instantiating-devices.rst
Signature · 1 line
2.17.1
#1 lore raw

PATCH v5 1/2 spi: add new_device/delete_device sysfs interface

Development boards such as the Jetson AGX Orin expose SPI buses on expansion headers (e.g. the 40-pin header) so that users can connect and interact with SPI peripherals from userspace. The standard way to get /dev/spidevB.C character device nodes for this purpose is to register spi_device instances backed by the spidev driver.

Today there is no viable way to do this on upstream kernels:

- The spidev driver rejects the bare "spidev" compatible string in DT, since spidev is a Linux software interface and not a description of real hardware.
- Vendor-specific compatible strings (e.g. "nvidia,tegra-spidev") have been rejected by DT maintainers for the same reason.

The I2C subsystem solved an analogous problem by exposing new_device/delete_device sysfs attributes on each adapter. Add the same interface to SPI host controllers, so that userspace (e.g. a systemd unit at boot) can instantiate SPI devices at runtime without needing anything in device-tree.

The new_device file accepts:

<modalias> <chip_select> [<max_speed_hz> [<mode>]]

where chip_select is required, while max_speed_hz and mode are optional and default to 0 if omitted. max_speed_hz == 0 is clamped to the controller's maximum by spi_setup(); mode == 0 selects SPI mode 0 (CPOL=0, CPHA=0).

The modalias is used both as the device identifier and as a driver_override, so that the device binds to the named driver directly. This is necessary because some drivers like spidev deliberately exclude generic names from their id_table.

Devices created this way are limited compared to those declared via DT or board files:

- No IRQ is assigned (the device gets IRQ 0 / no interrupt).
- No platform_data or device properties are attached.
- No OF node is associated with the device.

These limitations are acceptable for spidev, which only needs a registered spi_device to expose a character device to userspace.

Only devices created via new_device can be removed through delete_device; DT and platform devices are unaffected.

The sysfs attributes are gated behind CONFIG_SPI_DYNAMIC since this feature adds a new way of dynamically instantiating and removing SPI devices, and the add_lock locking in spi_unregister_controller() is already conditional on CONFIG_SPI_DYNAMIC.

A 'dead' flag on spi_controller prevents new device registration and list insertion after spi_unregister_controller() begins tearing down the controller. This avoids:

1. An ABBA deadlock between add_lock and the kernfs active reference held by sysfs store callbacks. add_lock is released before device_del() so that in-flight sysfs operations can drain.

2. Orphaned devices that could slip through after the userspace_clients cleanup but before device_del().

3. Use-after-free if __unregister frees a device that new_device_store() still references. An extra get_device() before spi_add_device() holds the device alive.

---
 drivers/spi/spi.c       | 217 ++++++++++++++++++++++++++++++++++++++--
 include/linux/spi/spi.h |  13 +++
 2 files changed, 224 insertions(+), 6 deletions(-)
drivers/spi/spi.c +211 -6
index 7001f5dce8bd..9042c19746b8 100644
@@ -296,11 +296,188 @@ static const struct attribute_group spi_controller_statistics_group = {
 	.attrs  = spi_controller_statistics_attrs,
 };
 
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+
+/*
+ * new_device_store - instantiate a new SPI device from userspace
+ *
+ * Takes parameters: <modalias> <chip_select> [<max_speed_hz> [<mode>]]
+ *
+ * Examples:
+ *   echo spidev 0 > new_device
+ *   echo spidev 0 10000000 > new_device
+ *   echo spidev 0 10000000 3 > new_device
+ */
+static ssize_t
+new_device_store(struct device *dev, struct device_attribute *attr,
+		 const char *buf, size_t count)
+{
+	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
+						   dev);
+	struct spi_device *spi;
+	char modalias[SPI_NAME_SIZE];
+	u16 chip_select;
+	u32 max_speed_hz = 0;
+	u32 mode = 0;
+	char *blank;
+	int n, res, status;
+
+	blank = strchr(buf, ' ');
+	if (!blank) {
+		dev_err(dev, "%s: Missing parameters\n", "new_device");
+		return -EINVAL;
+	}
+
+	if (blank - buf > SPI_NAME_SIZE - 1) {
+		dev_err(dev, "%s: Invalid device name\n", "new_device");
+		return -EINVAL;
+	}
+
+	memset(modalias, 0, sizeof(modalias));
+	memcpy(modalias, buf, blank - buf);
+
+	/*
+	 * sscanf fills only the fields it matches; unmatched optional
+	 * fields (max_speed_hz, mode) stay zero from initialisation above.
+	 * max_speed_hz == 0 is clamped to the controller max by spi_setup().
+	 * mode == 0 selects SPI mode 0 (CPOL=0, CPHA=0).
+	 */
+	res = sscanf(++blank, "%hu %u %u%n",
+		     &chip_select, &max_speed_hz, &mode, &n);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse chip select\n", "new_device");
+		return -EINVAL;
+	}
+
+	if (chip_select >= ctlr->num_chipselect) {
+		dev_err(dev, "%s: Chip select %u >= max %u\n", "new_device",
+			chip_select, ctlr->num_chipselect);
+		return -EINVAL;
+	}
+
+	spi = spi_alloc_device(ctlr);
+	if (!spi)
+		return -ENOMEM;
+
+	spi_set_chipselect(spi, 0, chip_select);
+	spi->max_speed_hz = max_speed_hz;
+	spi->mode = mode;
+	spi->cs_index_mask = BIT(0);
+	strscpy(spi->modalias, modalias, sizeof(spi->modalias));
+
+	/*
+	 * Set driver_override so that the device binds to the driver
+	 * named by modalias regardless of whether that driver's
+	 * id_table contains a matching entry.  This is needed because
+	 * some drivers (e.g. spidev) deliberately omit generic names
+	 * from their id_table.
+	 */
+	status = device_set_driver_override(&spi->dev, modalias);
+	if (status) {
+		spi_dev_put(spi);
+		return status;
+	}
+
+	/* Extra ref so concurrent __unregister cannot free the device */
+	get_device(&spi->dev);
+
+	status = spi_add_device(spi);
+	if (status) {
+		put_device(&spi->dev);
+		spi_dev_put(spi);
+		return status;
+	}
+
+	mutex_lock(&ctlr->userspace_clients_lock);
+	if (!ctlr->dead) {
+		list_add_tail(&spi->userspace_node, &ctlr->userspace_clients);
+		mutex_unlock(&ctlr->userspace_clients_lock);
+		put_device(&spi->dev);
+		dev_info(dev, "%s: Instantiated device %s at CS%u\n",
+			 "new_device", modalias, chip_select);
+		return count;
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+
+	/*
+	 * Controller is dying; __unregister will clean up the device.
+	 * Drop our extra ref and bail.
+	 */
+	put_device(&spi->dev);
+	return -ENODEV;
+}
+static DEVICE_ATTR_WO(new_device);
+
+static ssize_t
+delete_device_store(struct device *dev, struct device_attribute *attr,
+		    const char *buf, size_t count)
+{
+	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
+						   dev);
+	struct spi_device *spi, *next;
+	unsigned short cs;
+	char end;
+	int res;
+
+	res = sscanf(buf, "%hu%c", &cs, &end);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse chip select\n", "delete_device");
+		return -EINVAL;
+	}
+	if (res > 1 && end != '\n') {
+		dev_err(dev, "%s: Extra parameters\n", "delete_device");
+		return -EINVAL;
+	}
+
+	res = -ENOENT;
+	mutex_lock(&ctlr->userspace_clients_lock);
+	list_for_each_entry_safe(spi, next, &ctlr->userspace_clients,
+				 userspace_node) {
+		if (spi_get_chipselect(spi, 0) == cs) {
+			dev_info(dev, "%s: Deleting device %s at CS%u\n",
+				 "delete_device", spi->modalias, cs);
+
+			list_del(&spi->userspace_node);
+			spi_unregister_device(spi);
+			res = count;
+			break;
+		}
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+
+	if (res < 0)
+		dev_err(dev, "%s: Can't find device in list\n",
+			"delete_device");
+	return res;
+}
+static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, 0200, NULL,
+				   delete_device_store);
+
+static struct attribute *spi_controller_userspace_attrs[] = {
+	&dev_attr_new_device.attr,
+	&dev_attr_delete_device.attr,
+	NULL,
+};
+
+static const struct attribute_group spi_controller_userspace_group = {
+	.attrs = spi_controller_userspace_attrs,
+};
+
 static const struct attribute_group *spi_controller_groups[] = {
 	&spi_controller_statistics_group,
+	&spi_controller_userspace_group,
 	NULL,
 };
 
+#else /* !CONFIG_SPI_DYNAMIC */
+
+static const struct attribute_group *spi_controller_groups[] = {
+	&spi_controller_statistics_group,
+	NULL,
+};
+
+#endif /* CONFIG_SPI_DYNAMIC */
+
 static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
 					      struct spi_transfer *xfer,
 					      struct spi_message *msg)
@@ -724,10 +901,10 @@ static int __spi_add_device(struct spi_device *spi, struct spi_device *parent)
 		return status;
 
 	/* Controller may unregister concurrently */
-	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
-	    !device_is_registered(&ctlr->dev)) {
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	if (ctlr->dead)
 		return -ENODEV;
-	}
+#endif
 
 	if (ctlr->cs_gpiods) {
 		u8 cs;
@@ -3256,6 +3433,10 @@ struct spi_controller *__spi_alloc_controller(struct device *dev,
 	mutex_init(&ctlr->bus_lock_mutex);
 	mutex_init(&ctlr->io_mutex);
 	mutex_init(&ctlr->add_lock);
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	mutex_init(&ctlr->userspace_clients_lock);
+	INIT_LIST_HEAD(&ctlr->userspace_clients);
+#endif
 	ctlr->bus_num = -1;
 	ctlr->num_chipselect = 1;
 	ctlr->num_data_lanes = 1;
@@ -3633,8 +3814,35 @@ void spi_unregister_controller(struct spi_controller *ctlr)
 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
 		mutex_lock(&ctlr->add_lock);
 
+	/*
+	 * Mark dead and drain userspace_clients before __unregister,
+	 * since spi_unregister_device() doesn't do list_del() itself.
+	 */
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	mutex_lock(&ctlr->userspace_clients_lock);
+	ctlr->dead = true;
+	while (!list_empty(&ctlr->userspace_clients)) {
+		struct spi_device *spi;
+
+		spi = list_first_entry(&ctlr->userspace_clients,
+				       struct spi_device,
+				       userspace_node);
+		list_del(&spi->userspace_node);
+		spi_unregister_device(spi);
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+#endif
+
 	device_for_each_child(&ctlr->dev, NULL, __unregister);
 
+	/*
+	 * Release add_lock before device_del(): holding it would
+	 * deadlock against kernfs_drain waiting for in-flight sysfs
+	 * stores.  ctlr->dead prevents new device registration.
+	 */
+	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
+		mutex_unlock(&ctlr->add_lock);
+
 	/* First make sure that this controller was ever added */
 	mutex_lock(&board_lock);
 	found = idr_find(&spi_controller_idr, id);
@@ -3655,9 +3863,6 @@ void spi_unregister_controller(struct spi_controller *ctlr)
 		idr_remove(&spi_controller_idr, id);
 	mutex_unlock(&board_lock);
 
-	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
-		mutex_unlock(&ctlr->add_lock);
-
 	/*
 	 * Release the last reference on the controller if its driver
 	 * has not yet been converted to devm_spi_alloc_host/target().
include/linux/spi/spi.h +13 -0
index 7587b1c5d7ec..7a86749d2701 100644
@@ -250,6 +250,10 @@ struct spi_device {
 	u8			rx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
 	u8			num_rx_lanes;
 
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	struct list_head	userspace_node;
+#endif
+
 	/*
 	 * Likely need more hooks for more protocol options affecting how
 	 * the controller talks to each chip, like:
@@ -554,6 +558,9 @@ extern struct spi_device *devm_spi_new_ancillary_device(struct spi_device *spi,
  * @defer_optimize_message: set to true if controller cannot pre-optimize messages
  *	and needs to defer the optimization step until the message is actually
  *	being transferred
+ * @userspace_clients: list of SPI devices instantiated from userspace via
+ *	the sysfs new_device interface
+ * @userspace_clients_lock: mutex protecting @userspace_clients
  *
  * Each SPI controller can communicate with one or more @spi_device
  * children.  These make a small bus, sharing MOSI, MISO and SCK signals
@@ -809,6 +816,12 @@ struct spi_controller {
 	bool			queue_empty;
 	bool			must_async;
 	bool			defer_optimize_message;
+
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	struct list_head	userspace_clients;
+	struct mutex		userspace_clients_lock;
+	bool			dead;
+#endif
 };
 
 static inline void *spi_controller_get_devdata(struct spi_controller *ctlr)
Signature · 1 line
2.17.1
#2 lore raw

PATCH v5 2/2 docs: spi: add documentation for userspace device instantiation

In reply to Vishwaroop A

Document the new_device and delete_device sysfs attributes on SPI controllers:

- Documentation/spi/instantiating-devices.rst: describes when and why this interface is needed, accepted parameters, usage examples, and limitations.
- Documentation/ABI/testing/sysfs-class-spi-master: formal ABI entry for both attributes.

---
 .../ABI/testing/sysfs-class-spi-master        | 34 +++++++
 Documentation/spi/index.rst                   |  1 +
 Documentation/spi/instantiating-devices.rst   | 88 +++++++++++++++++++
 3 files changed, 123 insertions(+)
 create mode 100644 Documentation/ABI/testing/sysfs-class-spi-master
 create mode 100644 Documentation/spi/instantiating-devices.rst
Documentation/ABI/testing/sysfs-class-spi-master new file +34 -0
new file mode 100644
index 000000000000..b498be128bad
@@ -0,0 +1,34 @@
+What:		/sys/class/spi_master/spiB/new_device
+Date:		April 2026
+KernelVersion:	7.2
+Contact:	[email protected]
+Description:	(WO) Instantiate a new SPI device on bus B, where B
+		is the bus number (0, 1, 2, ...). Takes parameters
+		in the format:
+
+		<modalias> <chip_select> [<max_speed_hz> [<mode>]]
+
+		where modalias is the driver name, chip_select is the
+		CS line number, and max_speed_hz and mode are optional.
+
+		The device can later be removed with delete_device.
+
+		Only devices created via this interface can be removed
+		with delete_device; platform and DT devices are not
+		affected.
+
+		Example:
+		# echo spidev 0 > /sys/class/spi_master/spi0/new_device
+		# echo spidev 0 10000000 > /sys/class/spi_master/spi0/new_device
+		# echo spidev 0 10000000 3 > /sys/class/spi_master/spi0/new_device
+
+What:		/sys/class/spi_master/spiB/delete_device
+Date:		April 2026
+KernelVersion:	7.2
+Contact:	[email protected]
+Description:	(WO) Remove a SPI device previously created via
+		new_device. Takes a single parameter: the chip select
+		number of the device to remove.
+
+		Example:
+		# echo 0 > /sys/class/spi_master/spi0/delete_device
Documentation/spi/index.rst +1 -0
index ac0c2233ce48..3f723e2c07da 100644
@@ -8,6 +8,7 @@ Serial Peripheral Interface (SPI)
    :maxdepth: 1
 
    spi-summary
+   instantiating-devices
    spidev
    multiple-data-lanes
    butterfly
Documentation/spi/instantiating-devices.rst new file +88 -0

88 lines not on this page · raw message

Signature · 1 line
2.17.1
#3 lore raw

v6 cover spi: add new_device/delete_device sysfs interface

In reply to Vishwaroop A

Add I2C-style new_device/delete_device sysfs attributes to SPI host controllers, allowing userspace to instantiate and remove SPI devices at runtime without device-tree changes.

Patch 1 adds the new_device/delete_device attributes and the supporting infrastructure (userspace_clients list, locking, dead flag). Patch 2 adds the ABI and user-facing documentation.

Changes since v5:
- Rebased on next-20260707 (v7.2-rc2); applies cleanly.
- Added missing kernel-doc entries for the new struct fields (@userspace_node, @userspace_clients, @userspace_clients_lock, @dead).
- new_device_store(): reject chip_select > U8_MAX to avoid silent

    truncation in spi_set_chipselect(); parse with %u instead of %hu.

- new_device_store(): reject mode bits outside SPI_MODE_USER_MASK (mirrors spidev's SPI_IOC_WR_MODE32 filter).
- new_device_store(): drop the unused 'n' / '%n' from sscanf().
- Minor comment cleanup.

Changes since v4:
- Removed spi_unregister_device() call from new_device_store()'s ctlr->dead teardown path; it raced with device_for_each_child(__unregister) in spi_unregister_controller().

Changes since v3:
- Replaced holding add_lock across __spi_add_device() + list insertion (which caused an ABBA deadlock with kernfs) by a ctlr->dead flag checked under add_lock / userspace_clients_lock.
- Used a compile-time #if IS_ENABLED() guard for the ctlr->dead check in __spi_add_device(), since the dead field is conditional.

Changes since v2:
- Gated sysfs attributes and locking on CONFIG_SPI_DYNAMIC.

Changes since v1:
- Added locking to prevent races between new_device_store() and concurrent spi_unregister_controller().

Vishwaroop A (2):
spi: add new_device/delete_device sysfs interface
docs: spi: add documentation for userspace device instantiation

 .../ABI/testing/sysfs-class-spi-master        |  34 +++
 Documentation/spi/index.rst                   |   1 +
 Documentation/spi/instantiating-devices.rst   |  88 +++++++
 drivers/spi/spi.c                             | 238 +++++++++++++++++-
 include/linux/spi/spi.h                       |  21 ++
 5 files changed, 376 insertions(+), 6 deletions(-)
 create mode 100644 Documentation/ABI/testing/sysfs-class-spi-master
 create mode 100644 Documentation/spi/instantiating-devices.rst

base-commit: be5c93fa674f0fc3c8f359c2143abce6bbb422e6

Signature · 1 line
2.17.1
#4 lore raw

PATCH v6 1/2 spi: add new_device/delete_device sysfs interface

Development boards such as the Jetson AGX Orin expose SPI buses on expansion headers (e.g. the 40-pin header) so that users can connect and interact with SPI peripherals from userspace. The standard way to get /dev/spidevB.C character device nodes for this purpose is to register spi_device instances backed by the spidev driver.

Today there is no viable way to do this on upstream kernels:

- The spidev driver rejects the bare "spidev" compatible string in DT, since spidev is a Linux software interface and not a description of real hardware.
- Vendor-specific compatible strings (e.g. "nvidia,tegra-spidev") have been rejected by DT maintainers for the same reason.

The I2C subsystem solved an analogous problem by exposing new_device/delete_device sysfs attributes on each adapter. Add the same interface to SPI host controllers, so that userspace (e.g. a systemd unit at boot) can instantiate SPI devices at runtime without needing anything in device-tree.

The new_device file accepts:

<modalias> <chip_select> [<max_speed_hz> [<mode>]]

where chip_select is required, while max_speed_hz and mode are optional and default to 0 if omitted. max_speed_hz == 0 is clamped to the controller's maximum by spi_setup(); mode == 0 selects SPI mode 0 (CPOL=0, CPHA=0).

The modalias is used both as the device identifier and as a driver_override, so that the device binds to the named driver directly. This is necessary because some drivers like spidev deliberately exclude generic names from their id_table.

Devices created this way are limited compared to those declared via DT or board files:

- No IRQ is assigned (the device gets IRQ 0 / no interrupt).
- No platform_data or device properties are attached.
- No OF node is associated with the device.

These limitations are acceptable for spidev, which only needs a registered spi_device to expose a character device to userspace.

Only devices created via new_device can be removed through delete_device; DT and platform devices are unaffected.

The sysfs attributes are gated behind CONFIG_SPI_DYNAMIC since this feature adds a new way of dynamically instantiating and removing SPI devices, and the add_lock locking in spi_unregister_controller() is already conditional on CONFIG_SPI_DYNAMIC.

A 'dead' flag on spi_controller prevents new device registration and list insertion after spi_unregister_controller() begins tearing down the controller. This avoids:

1. An ABBA deadlock between add_lock and the kernfs active reference held by sysfs store callbacks. add_lock is released before device_del() so that in-flight sysfs operations can drain.

2. Orphaned devices that could slip through after the userspace_clients cleanup but before device_del().

3. Use-after-free if __unregister frees a device that new_device_store() still references. An extra get_device() before spi_add_device() holds the device alive.

---
 drivers/spi/spi.c       | 238 +++++++++++++++++++++++++++++++++++++++-
 include/linux/spi/spi.h |  21 ++++
 2 files changed, 253 insertions(+), 6 deletions(-)
drivers/spi/spi.c +232 -6
index d9e6b4b87c89..6bd4fbbd272b 100644
@@ -297,11 +297,209 @@ static const struct attribute_group spi_controller_statistics_group = {
 	.attrs  = spi_controller_statistics_attrs,
 };
 
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+
+/*
+ * new_device_store - instantiate a new SPI device from userspace
+ *
+ * Takes parameters: <modalias> <chip_select> [<max_speed_hz> [<mode>]]
+ *
+ * Examples:
+ *   echo spidev 0 > new_device
+ *   echo spidev 0 10000000 > new_device
+ *   echo spidev 0 10000000 3 > new_device
+ */
+static ssize_t
+new_device_store(struct device *dev, struct device_attribute *attr,
+		 const char *buf, size_t count)
+{
+	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
+						   dev);
+	struct spi_device *spi;
+	char modalias[SPI_NAME_SIZE];
+	unsigned int chip_select;
+	u32 max_speed_hz = 0;
+	u32 mode = 0;
+	char *blank;
+	int res, status;
+
+	blank = strchr(buf, ' ');
+	if (!blank) {
+		dev_err(dev, "%s: Missing parameters\n", "new_device");
+		return -EINVAL;
+	}
+
+	if (blank - buf > SPI_NAME_SIZE - 1) {
+		dev_err(dev, "%s: Invalid device name\n", "new_device");
+		return -EINVAL;
+	}
+
+	memset(modalias, 0, sizeof(modalias));
+	memcpy(modalias, buf, blank - buf);
+
+	/*
+	 * sscanf fills only the fields it matches; unmatched optional
+	 * fields (max_speed_hz, mode) stay zero from initialisation above.
+	 * max_speed_hz == 0 is clamped to the controller max by spi_setup().
+	 * mode == 0 selects SPI mode 0 (CPOL=0, CPHA=0).
+	 */
+	res = sscanf(++blank, "%u %u %u",
+		     &chip_select, &max_speed_hz, &mode);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse chip select\n", "new_device");
+		return -EINVAL;
+	}
+
+	/*
+	 * spi_device.chip_select[] is u8, so cap at U8_MAX independently of
+	 * ctlr->num_chipselect (which is u16 and may exceed 255).  Without
+	 * this, values in (U8_MAX, num_chipselect) would silently truncate
+	 * inside spi_set_chipselect() and select the wrong CS.
+	 */
+	if (chip_select > U8_MAX || chip_select >= ctlr->num_chipselect) {
+		dev_err(dev, "%s: Chip select %u out of range (num_chipselect=%u)\n",
+			"new_device", chip_select, ctlr->num_chipselect);
+		return -EINVAL;
+	}
+
+	/*
+	 * Reject kernel-internal mode bits (SPI_NO_TX, SPI_NO_RX,
+	 * SPI_TPM_HW_FLOW, ...).  These are set only by in-kernel drivers
+	 * that know they are safe on their controller/device pair and must
+	 * not be settable through a userspace-writable sysfs.  Matches
+	 * spidev's SPI_IOC_WR_MODE32 handling (drivers/spi/spidev.c).
+	 */
+	if (mode & ~(u32)SPI_MODE_USER_MASK) {
+		dev_err(dev, "%s: Invalid mode bits 0x%x\n", "new_device",
+			mode & ~(u32)SPI_MODE_USER_MASK);
+		return -EINVAL;
+	}
+
+	spi = spi_alloc_device(ctlr);
+	if (!spi)
+		return -ENOMEM;
+
+	spi_set_chipselect(spi, 0, chip_select);
+	spi->max_speed_hz = max_speed_hz;
+	spi->mode = mode;
+	spi->cs_index_mask = BIT(0);
+	strscpy(spi->modalias, modalias, sizeof(spi->modalias));
+
+	/*
+	 * Set driver_override so that the device binds to the driver
+	 * named by modalias regardless of whether that driver's
+	 * id_table contains a matching entry.  This is needed because
+	 * some drivers (e.g. spidev) deliberately omit generic names
+	 * from their id_table.
+	 */
+	status = device_set_driver_override(&spi->dev, modalias);
+	if (status) {
+		spi_dev_put(spi);
+		return status;
+	}
+
+	/* Extra ref so concurrent __unregister cannot free the device */
+	get_device(&spi->dev);
+
+	status = spi_add_device(spi);
+	if (status) {
+		put_device(&spi->dev);
+		spi_dev_put(spi);
+		return status;
+	}
+
+	mutex_lock(&ctlr->userspace_clients_lock);
+	if (!ctlr->dead) {
+		list_add_tail(&spi->userspace_node, &ctlr->userspace_clients);
+		mutex_unlock(&ctlr->userspace_clients_lock);
+		put_device(&spi->dev);
+		dev_info(dev, "%s: Instantiated device %s at CS%u\n",
+			 "new_device", modalias, chip_select);
+		return count;
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+
+	/*
+	 * Controller is dying; device_for_each_child(__unregister) in
+	 * spi_unregister_controller() handles the cleanup (it may already
+	 * have processed this device by the time we get here, since both
+	 * paths serialise on ctlr->add_lock).  Drop our extra ref and bail.
+	 */
+	put_device(&spi->dev);
+	return -ENODEV;
+}
+static DEVICE_ATTR_WO(new_device);
+
+static ssize_t
+delete_device_store(struct device *dev, struct device_attribute *attr,
+		    const char *buf, size_t count)
+{
+	struct spi_controller *ctlr = container_of(dev, struct spi_controller,
+						   dev);
+	struct spi_device *spi, *next;
+	unsigned short cs;
+	char end;
+	int res;
+
+	res = sscanf(buf, "%hu%c", &cs, &end);
+	if (res < 1) {
+		dev_err(dev, "%s: Can't parse chip select\n", "delete_device");
+		return -EINVAL;
+	}
+	if (res > 1 && end != '\n') {
+		dev_err(dev, "%s: Extra parameters\n", "delete_device");
+		return -EINVAL;
+	}
+
+	res = -ENOENT;
+	mutex_lock(&ctlr->userspace_clients_lock);
+	list_for_each_entry_safe(spi, next, &ctlr->userspace_clients,
+				 userspace_node) {
+		if (spi_get_chipselect(spi, 0) == cs) {
+			dev_info(dev, "%s: Deleting device %s at CS%u\n",
+				 "delete_device", spi->modalias, cs);
+
+			list_del(&spi->userspace_node);
+			spi_unregister_device(spi);
+			res = count;
+			break;
+		}
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+
+	if (res < 0)
+		dev_err(dev, "%s: Can't find device in list\n",
+			"delete_device");
+	return res;
+}
+static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, 0200, NULL,
+				   delete_device_store);
+
+static struct attribute *spi_controller_userspace_attrs[] = {
+	&dev_attr_new_device.attr,
+	&dev_attr_delete_device.attr,
+	NULL,
+};
+
+static const struct attribute_group spi_controller_userspace_group = {
+	.attrs = spi_controller_userspace_attrs,
+};
+
 static const struct attribute_group *spi_controller_groups[] = {
 	&spi_controller_statistics_group,
+	&spi_controller_userspace_group,
 	NULL,
 };
 
+#else /* !CONFIG_SPI_DYNAMIC */
+
+static const struct attribute_group *spi_controller_groups[] = {
+	&spi_controller_statistics_group,
+	NULL,
+};
+
+#endif /* CONFIG_SPI_DYNAMIC */
+
 static void spi_statistics_add_transfer_stats(struct spi_statistics __percpu *pcpu_stats,
 					      struct spi_transfer *xfer,
 					      struct spi_message *msg)
@@ -729,10 +927,10 @@ static int __spi_add_device(struct spi_device *spi, struct spi_device *parent)
 		return status;
 
 	/* Controller may unregister concurrently */
-	if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
-	    !device_is_registered(&ctlr->dev)) {
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	if (ctlr->dead)
 		return -ENODEV;
-	}
+#endif
 
 	if (ctlr->cs_gpiods) {
 		for (idx = 0; idx < spi->num_chipselect; idx++) {
@@ -3259,6 +3457,10 @@ struct spi_controller *__spi_alloc_controller(struct device *dev,
 	mutex_init(&ctlr->bus_lock_mutex);
 	mutex_init(&ctlr->io_mutex);
 	mutex_init(&ctlr->add_lock);
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	mutex_init(&ctlr->userspace_clients_lock);
+	INIT_LIST_HEAD(&ctlr->userspace_clients);
+#endif
 	ctlr->bus_num = -1;
 	ctlr->num_chipselect = 1;
 	ctlr->num_data_lanes = 1;
@@ -3620,8 +3822,35 @@ void spi_unregister_controller(struct spi_controller *ctlr)
 	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
 		mutex_lock(&ctlr->add_lock);
 
+	/*
+	 * Mark dead and drain userspace_clients before __unregister,
+	 * since spi_unregister_device() doesn't do list_del() itself.
+	 */
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	mutex_lock(&ctlr->userspace_clients_lock);
+	ctlr->dead = true;
+	while (!list_empty(&ctlr->userspace_clients)) {
+		struct spi_device *spi;
+
+		spi = list_first_entry(&ctlr->userspace_clients,
+				       struct spi_device,
+				       userspace_node);
+		list_del(&spi->userspace_node);
+		spi_unregister_device(spi);
+	}
+	mutex_unlock(&ctlr->userspace_clients_lock);
+#endif
+
 	device_for_each_child(&ctlr->dev, NULL, __unregister);
 
+	/*
+	 * Release add_lock before device_del(): holding it would
+	 * deadlock against kernfs_drain waiting for in-flight sysfs
+	 * stores.  ctlr->dead prevents new device registration.
+	 */
+	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
+		mutex_unlock(&ctlr->add_lock);
+
 	/* First make sure that this controller was ever added */
 	mutex_lock(&board_lock);
 	found = idr_find(&spi_controller_idr, id);
@@ -3641,9 +3870,6 @@ void spi_unregister_controller(struct spi_controller *ctlr)
 	if (found == ctlr)
 		idr_remove(&spi_controller_idr, id);
 	mutex_unlock(&board_lock);
-
-	if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
-		mutex_unlock(&ctlr->add_lock);
 }
 EXPORT_SYMBOL_GPL(spi_unregister_controller);
 
include/linux/spi/spi.h +21 -0
index 4c285d3ede1d..817fba2cb12b 100644
@@ -179,6 +179,8 @@ extern void spi_transfer_cs_change_delay_exec(struct spi_message *msg,
  * @num_tx_lanes: Number of transmit lanes wired up.
  * @rx_lane_map: Map of peripheral lanes (index) to controller lanes (value).
  * @num_rx_lanes: Number of receive lanes wired up.
+ * @userspace_node: entry on the parent controller's userspace_clients list
+ *	when this device was instantiated via the sysfs new_device interface
  *
  * A @spi_device is used to interchange data between an SPI target device
  * (usually a discrete chip) and CPU memory.
@@ -252,6 +254,10 @@ struct spi_device {
 	u8			rx_lane_map[SPI_DEVICE_DATA_LANE_CNT_MAX];
 	u8			num_rx_lanes;
 
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	struct list_head	userspace_node;
+#endif
+
 	/*
 	 * Likely need more hooks for more protocol options affecting how
 	 * the controller talks to each chip, like:
@@ -555,6 +561,12 @@ extern struct spi_device *devm_spi_new_ancillary_device(struct spi_device *spi,
  * @defer_optimize_message: set to true if controller cannot pre-optimize messages
  *	and needs to defer the optimization step until the message is actually
  *	being transferred
+ * @userspace_clients: list of SPI devices instantiated from userspace via
+ *	the sysfs new_device interface
+ * @userspace_clients_lock: mutex protecting @userspace_clients and @dead
+ * @dead: set to true when spi_unregister_controller() begins teardown;
+ *	prevents __spi_add_device() and new_device_store() from racing new
+ *	device registrations against controller shutdown
  *
  * Each SPI controller can communicate with one or more @spi_device
  * children.  These make a small bus, sharing MOSI, MISO and SCK signals
@@ -807,6 +819,15 @@ struct spi_controller {
 	bool			queue_empty;
 	bool			must_async;
 	bool			defer_optimize_message;
+
+#if IS_ENABLED(CONFIG_SPI_DYNAMIC)
+	/* List of userspace-instantiated devices; protected by @userspace_clients_lock */
+	struct list_head	userspace_clients;
+	/* Protects @userspace_clients and @dead against concurrent sysfs stores */
+	struct mutex		userspace_clients_lock;
+	/* Set true once spi_unregister_controller() has begun teardown */
+	bool			dead;
+#endif
 };
 
 static inline void *spi_controller_get_devdata(struct spi_controller *ctlr)
Signature · 1 line
2.17.1
maintainer
#5 lore raw
Quoted 7 lines · Vishwaroop A

Development boards such as the Jetson AGX Orin expose SPI buses on expansion headers (e.g. the 40-pin header) so that users can connect and interact with SPI peripherals from userspace. The standard way to get /dev/spidevB.C character device nodes for this purpose is to register spi_device instances backed by the spidev driver.

drivers/spi/spi.c static const struct attribute_group spi_controller_statistics_group = { · line 335

Quoted 8 lines
drivers/spi/spi.c +7 -0
+new_device_store(struct device *dev, struct device_attribute *attr,
+		 const char *buf, size_t count)
+{
 
+	if (blank - buf > SPI_NAME_SIZE - 1) {
+		dev_err(dev, "%s: Invalid device name\n", "new_device");
+		return -EINVAL;
+	}

What about empty names (" 0")?

drivers/spi/spi.c static const struct attribute_group spi_controller_statistics_group = { · line 492

Quoted 5 lines

static const struct attribute_group *spi_controller_groups[] = {

drivers/spi/spi.c +1 -0
 	&spi_controller_statistics_group,
+	&spi_controller_userspace_group,
 	NULL,
 };

It looks like there's an issue with cleanup here when a controller is probing, the userspace interface will appear when the device is registered but that's part way through setting up the controller, before we've finished sitting up the devices from the firmware and the queue. We probably need to manually register this as the last step of controller bringup, we can't defer the device for long enough as we need it to create the children.

#6 lore raw

PATCH v6 2/2 docs: spi: add documentation for userspace device instantiation

In reply to Vishwaroop A

Document the new_device and delete_device sysfs attributes on SPI controllers:

- Documentation/spi/instantiating-devices.rst: describes when and why this interface is needed, accepted parameters, usage examples, and limitations.
- Documentation/ABI/testing/sysfs-class-spi-master: formal ABI entry for both attributes.

---
 .../ABI/testing/sysfs-class-spi-master        | 34 +++++++
 Documentation/spi/index.rst                   |  1 +
 Documentation/spi/instantiating-devices.rst   | 88 +++++++++++++++++++
 3 files changed, 123 insertions(+)
 create mode 100644 Documentation/ABI/testing/sysfs-class-spi-master
 create mode 100644 Documentation/spi/instantiating-devices.rst
Documentation/ABI/testing/sysfs-class-spi-master new file +34 -0
new file mode 100644
index 000000000000..b498be128bad
@@ -0,0 +1,34 @@
+What:		/sys/class/spi_master/spiB/new_device
+Date:		April 2026
+KernelVersion:	7.2
+Contact:	[email protected]
+Description:	(WO) Instantiate a new SPI device on bus B, where B
+		is the bus number (0, 1, 2, ...). Takes parameters
+		in the format:
+
+		<modalias> <chip_select> [<max_speed_hz> [<mode>]]
+
+		where modalias is the driver name, chip_select is the
+		CS line number, and max_speed_hz and mode are optional.
+
+		The device can later be removed with delete_device.
+
+		Only devices created via this interface can be removed
+		with delete_device; platform and DT devices are not
+		affected.
+
+		Example:
+		# echo spidev 0 > /sys/class/spi_master/spi0/new_device
+		# echo spidev 0 10000000 > /sys/class/spi_master/spi0/new_device
+		# echo spidev 0 10000000 3 > /sys/class/spi_master/spi0/new_device
+
+What:		/sys/class/spi_master/spiB/delete_device
+Date:		April 2026
+KernelVersion:	7.2
+Contact:	[email protected]
+Description:	(WO) Remove a SPI device previously created via
+		new_device. Takes a single parameter: the chip select
+		number of the device to remove.
+
+		Example:
+		# echo 0 > /sys/class/spi_master/spi0/delete_device
Documentation/spi/index.rst +1 -0
index ac0c2233ce48..3f723e2c07da 100644
@@ -8,6 +8,7 @@ Serial Peripheral Interface (SPI)
    :maxdepth: 1
 
    spi-summary
+   instantiating-devices
    spidev
    multiple-data-lanes
    butterfly
Documentation/spi/instantiating-devices.rst new file +88 -0

88 lines not on this page · raw message

Signature · 1 line
2.17.1
maintainer
#7 lore raw
In reply to Vishwaroop A
Quoted 3 lines · Vishwaroop A

Add I2C-style new_device/delete_device sysfs attributes to SPI host controllers, allowing userspace to instantiate and remove SPI devices at runtime without device-tree changes.

Please don't send new patches in reply to old patches or serieses, this makes it harder for both people and tools to understand what is going on - it can bury things in mailboxes and make it difficult to keep track of what current patches are, both for the new patches and the old ones.