Skip to contentSkip to conversation

gpio: consumer: new virtual driver

PATCH Superseded Bartosz Golaszewski 2 participants 3 messages Aug 9, 2023 – Aug 11, 2023

Subsystems (2)

v3 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/1 gpio: consumer: new virtual driver

From: Bartosz Golaszewski <[email protected]>

The GPIO subsystem has a serious problem with undefined behavior and use-after-free bugs on hot-unplug of GPIO chips. This can be considered a corner-case by some as most GPIO controllers are enabled early in the boot process and live until the system goes down but most GPIO drivers do allow unbind over sysfs, many are loadable modules that can be (force) unloaded and there are also GPIO devices that can be dynamically detached, for instance CP2112 which is a USB GPIO expender.

Bugs can be triggered both from user-space as well as by in-kernel users. We have the means of testing it from user-space via the character device but the issues manifest themselves differently in the kernel.

This is a proposition of adding a new virtual driver - a configurable GPIO consumer that can be configured over configfs (similarly to gpio-sim).

The configfs interface allows users to create dynamic GPIO lookup tables that are registered with the GPIO subsystem. Every config group represents a consumer device. Every sub-group represents a single GPIO lookup. The device can work in three modes: just keeping the line active, toggling it every second or requesting its interrupt and reporting edges. Every lookup allows to specify the key, offset and flags as per the lookup struct defined in linux/gpio/machine.h.

The module together with gpio-sim allows to easily trigger kernel hot-unplug errors. A simple use-case is to create a simulated chip, setup the consumer to lookup one of its lines in 'monitor' mode, unbind the simulator, unbind the consumer and observe the fireworks in dmesg.

This driver is aimed as a helper in tackling the hot-unplug problem in GPIO as well as basis for future regression testing once the fixes are upstream.

---
RFC -> v2:
- add documentation
- fix various issues pointed out by Andy: use struct_size() where applicable, improve the logic when storing the 'live' property, improve log messages, remove commas in terminators, etc.

v2 -> v3:
- use cleanup.h interfaces
- add some clarifying commets
- more minor code tweaks

 .../admin-guide/gpio/gpio-consumer.rst        | 111 ++
 drivers/gpio/Kconfig                          |   7 +
 drivers/gpio/Makefile                         |   1 +
 drivers/gpio/gpio-consumer.c                  | 961 ++++++++++++++++++
 4 files changed, 1080 insertions(+)
 create mode 100644 Documentation/admin-guide/gpio/gpio-consumer.rst
 create mode 100644 drivers/gpio/gpio-consumer.c
Documentation/admin-guide/gpio/gpio-consumer.rst new file +111 -0
new file mode 100644
index 000000000000..436af3eec4ab
@@ -0,0 +1,111 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+Virtual GPIO Consumer
+=====================
+
+The virtual GPIO Consumer module allows users to create dynamic GPIO lookup
+tables using the exposed configfs interface and instantiate virtual GPIO
+consumer devices that retrieve and use GPIOs using these tables.
+
+Creating GPIO consumers
+-----------------------
+
+The gpio-consumer module registers a configfs subsystem called
+``'gpio-consumer'``. For details of the configfs filesystem, please refer to
+the configfs documentation.
+
+The user can create a hierarchy of configfs groups and items as well as modify
+values of exposed attributes. Once the consumer is instantiated, this hierarchy
+will be translated to appropriate device properties. The general structure is:
+
+**Group:** ``/config/gpio-consumer``
+
+This is the top directory of the gpio-consumer configfs tree.
+
+**Group:** ``/config/gpio-consumer/consumer-device``
+
+**Attribute:** ``/config/gpio-consumer/gpio-device/function``
+
+**Attribute:** ``/config/gpio-consumer/gpio-device/live``
+
+This is a directory representing a GPIO consumer device. The ``'function'``
+attribute defines how the device will use requested GPIOs. It takes the
+following values: ``'active'`` - GPIOs will be requested as output-high and
+kept in this state until the device is unbound, ``'toggle'`` - GPIOs will
+be requested in output mode and then toggled periodically (every second)
+between 1 and 0, ``'monitor'`` - GPIOs will be requested in input mode, then
+requested as interrupts and their firing reported in the kernel log.
+
+The ``'live'`` attribute allows to trigger the actual creation of the device
+once it's fully configured. The accepted values are: ``'1'`` to enable the
+virtual device and ``'0'`` to disable and tear it down.
+
+Creating GPIO lookup tables
+---------------------------
+
+User can create a number of configfs groups under the device group with the
+following properties:
+
+**Group:** ``/config/gpio-consumer/consumer-device/lookupX``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/key``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/offset``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/drive``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/pull``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/active_low``
+
+**Attribute:** ``/config/gpio-consumer/consumer-device/lookupX/transitory``
+
+This group represents a single entry in the GPIO lookup table. The name of the
+sub-directory maps to the ``'con_id'`` field of ``'struct gpiod_lookup'``. The
+``'key'`` attribute represents either the name of the chip this GPIO belongs to
+or the GPIO line name. This depends on the value of the ``'offset'`` attribute:
+if its value is >= 0, then ``'key'`` represents the label of the chip to lookup
+while ``'offset'`` represents the offset of the line in that chip. If
+``'offset'`` is < 0, then ``'key'`` represents the name of the line.
+
+The remaining attributes map to the ``'flags'`` field of the GPIO lookup struct.
+The first two take string values as arguments:
+
+**``'drive'``:** ``'push-pull'``, ``'open-drain'``, ``'open-source'``
+**``'pull'``:** ``'pull-up'``, ``'pull-down'``, ``'pull-disabled'``, ``'as-is'``
+
+``'active_low'`` and ``'transitory'`` are boolean attributes.
+
+Activating GPIO consumers
+-------------------------
+
+Once the confiuration is complete, the ``'live'`` attribute must be set to 1 in
+order to instantiate the consumer. It can be set back to 0 to destroy the
+virtual devices. The module will synchronously wait for the new simulated device
+to be successfully probed and if this doesn't happen, writing to ``'live'`` will
+result in an error.
+
+Device-tree
+-----------
+
+Virtual GPIO consumers can also be defined in device-tree. The compatible string
+must be: ``"gpio-virtual-consumer"``. Supported properties are:
+
+  ``"gpio-virtual-consumer,function"`` - function of the virtual device
+  ``"gpio-virtual-consumer,lines"`` - list of lookup keys
+
+An example device-tree code defining a virtual GPIO consumer:
+
+.. code-block :: none
+
+    gpio-virt-consumer {
+        compatible = "gpio-virtual-consumer";
+
+        foo-gpios = <&gpio0 5 GPIO_ACTIVE_LOW>;
+        bar-gpios = <&gpio0 6 0>;
+
+        gpio-virtual-consumer,function = "toggle";
+        gpio-virtual-consumer,lines = "foo", "bar";
+    };
+
+.. SPDX-License-Identifier: GPL-2.0-or-later
drivers/gpio/Kconfig +7 -0
index e382dfebad7c..c152fcf6c54f 100644
@@ -1762,6 +1762,13 @@ config GPIO_AGGREGATOR
 	      industrial control context, to be operated from userspace using
 	      the GPIO chardev interface.
 
+config GPIO_CONSUMER
+	tristate "GPIO Consumer Testing Module"
+	select CONFIGFS_FS
+	help
+	  This enables the configurable, configfs-based virtual GPIO consumer
+	  testing driver.
+
 config GPIO_LATCH
 	tristate "GPIO latch driver"
 	help
drivers/gpio/Makefile +1 -0
index c3ac51d47aa9..268e8f65f3c8 100644
@@ -46,6 +46,7 @@ obj-$(CONFIG_GPIO_BT8XX)		+= gpio-bt8xx.o
 obj-$(CONFIG_GPIO_CADENCE)		+= gpio-cadence.o
 obj-$(CONFIG_GPIO_CLPS711X)		+= gpio-clps711x.o
 obj-$(CONFIG_GPIO_SNPS_CREG)		+= gpio-creg-snps.o
+obj-$(CONFIG_GPIO_CONSUMER)		+= gpio-consumer.o
 obj-$(CONFIG_GPIO_CRYSTAL_COVE)		+= gpio-crystalcove.o
 obj-$(CONFIG_GPIO_CS5535)		+= gpio-cs5535.o
 obj-$(CONFIG_GPIO_DA9052)		+= gpio-da9052.o
drivers/gpio/gpio-consumer.c new file +961 -0

961 lines not on this page · raw message

Signature · 1 line
2.39.2
#1 lore raw
Quoted 33 lines · Bartosz Golaszewski

The GPIO subsystem has a serious problem with undefined behavior and use-after-free bugs on hot-unplug of GPIO chips. This can be considered a corner-case by some as most GPIO controllers are enabled early in the boot process and live until the system goes down but most GPIO drivers do allow unbind over sysfs, many are loadable modules that can be (force) unloaded and there are also GPIO devices that can be dynamically detached, for instance CP2112 which is a USB GPIO expender.

Bugs can be triggered both from user-space as well as by in-kernel users. We have the means of testing it from user-space via the character device but the issues manifest themselves differently in the kernel.

This is a proposition of adding a new virtual driver - a configurable GPIO consumer that can be configured over configfs (similarly to gpio-sim).

The configfs interface allows users to create dynamic GPIO lookup tables that are registered with the GPIO subsystem. Every config group represents a consumer device. Every sub-group represents a single GPIO lookup. The device can work in three modes: just keeping the line active, toggling it every second or requesting its interrupt and reporting edges. Every lookup allows to specify the key, offset and flags as per the lookup struct defined in linux/gpio/machine.h.

The module together with gpio-sim allows to easily trigger kernel hot-unplug errors. A simple use-case is to create a simulated chip, setup the consumer to lookup one of its lines in 'monitor' mode, unbind the simulator, unbind the consumer and observe the fireworks in dmesg.

This driver is aimed as a helper in tackling the hot-unplug problem in GPIO as well as basis for future regression testing once the fixes are upstream.

...

drivers/gpio/gpio-consumer.c line 94

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+static void gpio_consumer_on_timer(struct timer_list *timer)
+{
+	struct gpio_consumer_timer_data *timer_data = to_timer_data(timer);
+
+	timer_data->val = timer_data->val ? 1 : 0;

I guess it should be 0 : 1.

Quoted 3 lines
drivers/gpio/gpio-consumer.c new file +3 -0
+	gpiod_set_value_cansleep(timer_data->desc, timer_data->val);
+	mod_timer(&timer_data->timer, jiffies + msecs_to_jiffies(1000));
+}

...

drivers/gpio/gpio-consumer.c line 301

Quoted 7 lines
drivers/gpio/gpio-consumer.c new file +6 -0
+static ssize_t
+gpio_consumer_lookup_config_key_show(struct config_item *item, char *page)
+{
+	struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+	struct gpio_consumer_device *dev = lookup->parent;
 
+	int ret;

Why is it needed now? Seems you were too fast to send v3, look at my comments in v2 thread.

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+	scoped_guard(mutex, &dev->lock)
+		ret = sprintf(page, "%s\n", lookup->key);
+
+	return ret;
+}

...

drivers/gpio/gpio-consumer.c line 318

Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+static ssize_t
+gpio_consumer_lookup_config_key_store(struct config_item *item,
+				      const char *page, size_t count)
+{
+	struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+	struct gpio_consumer_device *dev = lookup->parent;
+	char *key __free(kfree) = NULL;
+	char *stripped;
+
+	key = kstrndup(page, count, GFP_KERNEL);

skip_spaces() will allow you to get rid of memmove().

drivers/gpio/gpio-consumer.c line 323

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+	if (!key)
+		return -ENOMEM;
+
+	stripped = strstrip(key);
+	memmove(key, stripped, strlen(stripped) + 1);

And this become something like

	/* Get rid of trailing newline and spaces */
	strim(key);
Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+	guard(mutex)(&dev->lock);
+
+	if (gpio_consumer_device_is_live_unlocked(dev))
+		return -EBUSY;
+
+	kfree(lookup->key);
+	lookup->key = no_free_ptr(key);
+
+	return count;
+}

...

drivers/gpio/gpio-consumer.c line 396

Quoted 12 lines
drivers/gpio/gpio-consumer.c new file +11 -0
+static enum gpio_lookup_flags
+gpio_consumer_lookup_get_flags(struct config_item *item)
+{
+	struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+	struct gpio_consumer_device *dev = lookup->parent;
+	enum gpio_lookup_flags flags;
+
+	scoped_guard(mutex, &dev->lock)
 
+		flags = lookup->flags;
+
+	return flags;
	guard()
	return lookup->flags;

?

Quoted 1 line

+}

...

Quoted 6 lines
drivers/gpio/gpio-consumer.c new file +6 -0
+static ssize_t
+gpio_consumer_device_config_live_store(struct config_item *item,
+				       const char *page, size_t count)
+{
+	struct gpio_consumer_device *dev = to_gpio_consumer_device(item);
+	bool live;

drivers/gpio/gpio-consumer.c line 743

Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+	int ret;
+
+	ret = kstrtobool(page, &live);
+	if (ret)
+		return ret;
+
+	guard(mutex)(&dev->lock);
+
+	if (live == gpio_consumer_device_is_live_unlocked(dev))
+		ret = -EPERM;
		return ... ?

drivers/gpio/gpio-consumer.c line 744

Quoted 1 line
drivers/gpio/gpio-consumer.c new file +1 -0
+	else if (live)
	if () ?

drivers/gpio/gpio-consumer.c line 746

Quoted 3 lines
drivers/gpio/gpio-consumer.c new file +2 -0
+		ret = gpio_consumer_device_activate_unlocked(dev);
 
+	else

drop it ?

Quoted 4 lines
drivers/gpio/gpio-consumer.c new file +4 -0
+		gpio_consumer_device_deactivate_unlocked(dev);
+
+	return ret ?: count;
+}
Signature · 2 lines
With Best Regards,
Andy Shevchenko
#2 lore raw
Quoted 38 lines · Andy Shevchenko
Quoted 33 lines · Bartosz Golaszewski

The GPIO subsystem has a serious problem with undefined behavior and use-after-free bugs on hot-unplug of GPIO chips. This can be considered a corner-case by some as most GPIO controllers are enabled early in the boot process and live until the system goes down but most GPIO drivers do allow unbind over sysfs, many are loadable modules that can be (force) unloaded and there are also GPIO devices that can be dynamically detached, for instance CP2112 which is a USB GPIO expender.

Bugs can be triggered both from user-space as well as by in-kernel users. We have the means of testing it from user-space via the character device but the issues manifest themselves differently in the kernel.

This is a proposition of adding a new virtual driver - a configurable GPIO consumer that can be configured over configfs (similarly to gpio-sim).

The configfs interface allows users to create dynamic GPIO lookup tables that are registered with the GPIO subsystem. Every config group represents a consumer device. Every sub-group represents a single GPIO lookup. The device can work in three modes: just keeping the line active, toggling it every second or requesting its interrupt and reporting edges. Every lookup allows to specify the key, offset and flags as per the lookup struct defined in linux/gpio/machine.h.

The module together with gpio-sim allows to easily trigger kernel hot-unplug errors. A simple use-case is to create a simulated chip, setup the consumer to lookup one of its lines in 'monitor' mode, unbind the simulator, unbind the consumer and observe the fireworks in dmesg.

This driver is aimed as a helper in tackling the hot-unplug problem in GPIO as well as basis for future regression testing once the fixes are upstream.

...

Quoted 8 lines

drivers/gpio/gpio-consumer.c line 94

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+static void gpio_consumer_on_timer(struct timer_list *timer)
+{
+     struct gpio_consumer_timer_data *timer_data = to_timer_data(timer);
+
+     timer_data->val = timer_data->val ? 1 : 0;

I guess it should be 0 : 1.

Eek!

Quoted 44 lines
Quoted 3 lines
drivers/gpio/gpio-consumer.c new file +3 -0
+     gpiod_set_value_cansleep(timer_data->desc, timer_data->val);
+     mod_timer(&timer_data->timer, jiffies + msecs_to_jiffies(1000));
+}

...

drivers/gpio/gpio-consumer.c line 301

Quoted 7 lines
drivers/gpio/gpio-consumer.c new file +6 -0
+static ssize_t
+gpio_consumer_lookup_config_key_show(struct config_item *item, char *page)
+{
+     struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+     struct gpio_consumer_device *dev = lookup->parent;
 
+     int ret;

Why is it needed now? Seems you were too fast to send v3, look at my comments in v2 thread.

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+     scoped_guard(mutex, &dev->lock)
+             ret = sprintf(page, "%s\n", lookup->key);
+
+     return ret;
+}

...

drivers/gpio/gpio-consumer.c line 318

Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+static ssize_t
+gpio_consumer_lookup_config_key_store(struct config_item *item,
+                                   const char *page, size_t count)
+{
+     struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+     struct gpio_consumer_device *dev = lookup->parent;
+     char *key __free(kfree) = NULL;
+     char *stripped;
+
+     key = kstrndup(page, count, GFP_KERNEL);

skip_spaces() will allow you to get rid of memmove().

drivers/gpio/gpio-consumer.c line 323

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +5 -0
+     if (!key)
+             return -ENOMEM;
+
+     stripped = strstrip(key);
+     memmove(key, stripped, strlen(stripped) + 1);
Quoted 5 lines

And this become something like

        /* Get rid of trailing newline and spaces */
        strim(key);

I did it this way for v3.

Quoted 56 lines
Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+     guard(mutex)(&dev->lock);
+
+     if (gpio_consumer_device_is_live_unlocked(dev))
+             return -EBUSY;
+
+     kfree(lookup->key);
+     lookup->key = no_free_ptr(key);
+
+     return count;
+}

...

drivers/gpio/gpio-consumer.c line 396

Quoted 12 lines
drivers/gpio/gpio-consumer.c new file +11 -0
+static enum gpio_lookup_flags
+gpio_consumer_lookup_get_flags(struct config_item *item)
+{
+     struct gpio_consumer_lookup *lookup = to_gpio_consumer_lookup(item);
+     struct gpio_consumer_device *dev = lookup->parent;
+     enum gpio_lookup_flags flags;
+
+     scoped_guard(mutex, &dev->lock)
 
+             flags = lookup->flags;
+
+     return flags;
        guard()
        return lookup->flags;

?

Quoted 1 line

+}

...

Quoted 6 lines
drivers/gpio/gpio-consumer.c new file +6 -0
+static ssize_t
+gpio_consumer_device_config_live_store(struct config_item *item,
+                                    const char *page, size_t count)
+{
+     struct gpio_consumer_device *dev = to_gpio_consumer_device(item);
+     bool live;

drivers/gpio/gpio-consumer.c line 743

Quoted 10 lines
drivers/gpio/gpio-consumer.c new file +10 -0
+     int ret;
+
+     ret = kstrtobool(page, &live);
+     if (ret)
+             return ret;
+
+     guard(mutex)(&dev->lock);
+
+     if (live == gpio_consumer_device_is_live_unlocked(dev))
+             ret = -EPERM;
                return ... ?
Quoted 1 line

+ else if (live)

Quoted 7 lines
        if () ?

drivers/gpio/gpio-consumer.c line 746

Quoted 3 lines
drivers/gpio/gpio-consumer.c new file +2 -0
+             ret = gpio_consumer_device_activate_unlocked(dev);
 
+     else

drop it ?

We need to return count, not ret so this version is clearer.

Bart

Quoted 11 lines

drivers/gpio/gpio-consumer.c line 750

Quoted 5 lines
drivers/gpio/gpio-consumer.c new file +4 -0
+             gpio_consumer_device_deactivate_unlocked(dev);
+
+     return ret ?: count;
+}

--
With Best Regards,
Andy Shevchenko