Skip to contentSkip to conversation

rust: Add basic GPIO consumer abstractions

PATCH In review Kohei Ito 6 participants 20 messages Sep 6 – Oct 3

Subsystems (2)
lore
Share & tools
lore

Kohei Ito

author
#0 lore raw

cover rust: Add basic GPIO consumer abstractions

This series introduces basic GPIO consumer abstractions for Rust.

- Patch 1 adds the top-level GPIO module with minimal common definitions.
- Patch 2 adds the initial GPIO consumer (gpio_desc) abstraction.
- Patch 3 adds a sample driver to demonstrate the use of the Rust GPIO APIs.

---
Kohei Ito (3):
rust: gpio: add GPIO module with common definitions
rust: gpio: Add basic consumer abstractions
sample: rust: Add GPIO consumer sample driver

 rust/bindings/bindings_helper.h    |   2 +
 rust/kernel/gpio.rs                | 154 +++++++++++++
 rust/kernel/gpio/consumer.rs       | 437 +++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs                 |   2 +
 samples/rust/Kconfig               |  11 +
 samples/rust/Makefile              |   1 +
 samples/rust/rust_gpio_consumer.rs | 156 +++++++++++++
 7 files changed, 763 insertions(+)

---
base-commit: 8d3ae59288f1e7d58d76558a6ee96d533bc5019f
change-id: 20260905-add-rust-gpio-consumer-8799f86bbbfd

Best regards,

Signature · 1 line
Kohei Ito <[email protected]>
author
#1 lore raw

PATCH 1/3 rust: gpio: add GPIO module with common definitions

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/gpio.rs             | 152 ++++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 3 files changed, 155 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index 1124785e210b..98b048b36771 100644
@@ -61,6 +61,7 @@
 #include <linux/file.h>
 #include <linux/firmware.h>
 #include <linux/fs.h>
+#include <linux/gpio/defs.h>
 #include <linux/i2c.h>
 #include <linux/interrupt.h>
 #include <linux/io-pgtable.h>
rust/kernel/gpio.rs new file +152 -0

152 lines not on this page · raw message

rust/kernel/lib.rs +2 -0
index 9512af7156df..6c96c1269249 100644
@@ -73,6 +73,8 @@
 pub mod firmware;
 pub mod fmt;
 pub mod fs;
+#[cfg(CONFIG_GPIOLIB)]
+pub mod gpio;
 #[cfg(CONFIG_GPU_BUDDY = "y")]
 pub mod gpu;
 #[cfg(CONFIG_I2C = "y")]
Signature · 1 line
2.50.1
#2 lore raw

Re: [PATCH 1/3] rust: gpio: add GPIO module with common definitions

Quoted 3 lines · Kohei Ito

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

Thanks & welcome!

I see you Cc'd linux-gpio, which is good, but the GPIO maintainers should be Cc'd too, since they are the ones that will be deciding on this -- doing it for you in this one so that they are in the loop.

By the way, it is nice to see GPIO again :) Now that some years have passed, how does it compare to

https://lwn.net/Articles/863459/

?

Cheers,
Miguel

reviewer
#3 lore raw

Re: [PATCH 1/3] rust: gpio: add GPIO module with common definitions

Quoted 11 lines · Miguel Ojeda
Quoted 3 lines · Kohei Ito

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

Thanks & welcome!

I see you Cc'd linux-gpio, which is good, but the GPIO maintainers should be Cc'd too, since they are the ones that will be deciding on this -- doing it for you in this one so that they are in the loop.

Quoted 6 lines

By the way, it is nice to see GPIO again :) Now that some years have passed, how does it compare to

https://lwn.net/Articles/863459/

?

This is possibily also a show case for all our I/O projection and register macro work :)

Best,
Gary

author
#4 lore raw

Re: [PATCH 1/3] rust: gpio: add GPIO module with common definitions

Hi, Miguel and Gary,

Quoted 11 lines · Gary Guo
Quoted 10 lines · Miguel Ojeda
Quoted 3 lines · Kohei Ito

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

Thanks & welcome!

I see you Cc'd linux-gpio, which is good, but the GPIO maintainers should be Cc'd too, since they are the ones that will be deciding on this -- doing it for you in this one so that they are in the loop.

Thank you for adding the GPIO maintainers. I'll make sure to Cc them in future revisions.

Quoted 9 lines
Quoted 6 lines

By the way, it is nice to see GPIO again :) Now that some years have passed, how does it compare to

https://lwn.net/Articles/863459/

?

This is possibily also a show case for all our I/O projection and register macro work :)

Thank you for the pointer. I was not aware of the past GPIO abstractions [1].

As I understand it, the past GPIO work focused on the GPIO driver APIs (include/linux/gpio/driver.h), i.e., for the drivers that provide GPIO functionality, mostly present in drivers/gpio.

On the other hand, this series implements GPIO consumer APIs (include/linux/gpio/consumer.h), i.e., for the drivers that use GPIOs, such as drivers/leds/leds-gpio.c and drivers/reset/reset-gpio.c.

I assume that the GPIO driver abstractions will be implemented later in rust/kernel/gpio/driver.rs.

[1] https://github.com/Rust-for-Linux/linux/blob/rust/rust/kernel/gpio.rs

    (Current hash: 18b7491480025420896e0c8b73c98475c3806c6f)

Best regards,
Kohei Ito

maintainer
#5 lore raw

Re: [PATCH 1/3] rust: gpio: add GPIO module with common definitions

In reply to Kohei Ito

Hi Kohei,

thanks for your patch!

Quoted 2 lines · Kohei Ito

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

Describe what you want to enable by this patch.

- Enabling in-kernel Rust code to use things from the GPIO subsystem? (It looks like so.)

- Writing GPIO drivers in rust? (It seems like not.)

Quoted 1 line

(...)

rust/kernel/gpio.rs line 57

Quoted 3 lines
rust/kernel/gpio.rs new file +3 -0
+/// Describes the logical GPIO level, i.e. taking the ACTIVE_LOW status into account.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum LogicalLineLevel {

Neat!

rust/kernel/gpio.rs line 107

Quoted 4 lines
rust/kernel/gpio.rs new file +4 -0
+/// Describes the raw GPIO level, i.e. the value of its physical line without regard for its
+/// ACTIVE_LOW status.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PhysicalLineLevel {

No thanks.

We want to hide the actual physical line level inside the gpiolib (encapsulation).

We should not expose the physical line level at all unless there is a consumer in the kernel that absolutely needs this, and there is none.

Yours,
Linus Walleij

author
#6 lore raw

Re: [PATCH 1/3] rust: gpio: add GPIO module with common definitions

Hi Linus,

thank you for your comments.

Quoted 9 lines
Quoted 2 lines

Add the top-level GPIO module with minimal common definitions. This module is the basis for future Rust GPIO extensions.

Describe what you want to enable by this patch.

- Enabling in-kernel Rust code to use things from the GPIO subsystem? (It looks like so.)

- Writing GPIO drivers in rust? (It seems like not.)

This patch is the first step to enable in-kernel Rust code to use things from the GPIO subsystem. I'll clarify this in the commit message. The patch series does not add Rust GPIO provider APIs or Rust GPIO provider drivers, but it is intended to be the basis for them.

Quoted 7 lines

rust/kernel/gpio.rs line 107

Quoted 4 lines
rust/kernel/gpio.rs new file +4 -0
+/// Describes the raw GPIO level, i.e. the value of its physical line without regard for its
+/// ACTIVE_LOW status.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PhysicalLineLevel {

No thanks.

Quoted 6 lines

We want to hide the actual physical line level inside the gpiolib (encapsulation).

We should not expose the physical line level at all unless there is a consumer in the kernel that absolutely needs this, and there is none.

Sure. I have no need to use the physical line level right now, so I'll remove it and the related definitions.

Best regards,
Kohei Ito

author
#7 lore raw

PATCH 2/3 rust: gpio: Add basic consumer abstractions

In reply to Kohei Ito

Add basic abstractions for GPIO consumer APIs.

Due to a bindgen issue that may generate the wrong type for enum types, gpio/consumer.h is included at the top of bindings_helper.h as a temporary workaround. Once the issue is resolved, it can be moved back to its proper alphabetical position.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/gpio.rs             |   2 +
 rust/kernel/gpio/consumer.rs    | 437 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 440 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index 98b048b36771..30985c102c70 100644
@@ -26,6 +26,7 @@
  * This workaround may not be possible in some cases, depending on how the C
  * headers are set up.
  */
+#include <linux/gpio/consumer.h>
 #include <linux/hrtimer_types.h>
 
 #include <linux/acpi.h>
rust/kernel/gpio.rs +2 -0
index 819efc8a0c05..40b6c64e8f5e 100644
@@ -11,6 +11,8 @@
     prelude::*, //
 };
 
+pub mod consumer;
+
 /// Describes GPIO direction.
 #[derive(Clone, Copy, PartialEq, Eq)]
 #[repr(u32)]
rust/kernel/gpio/consumer.rs new file +437 -0

437 lines not on this page · raw message

Signature · 1 line
2.50.1
#8 lore raw

Re: [PATCH 2/3] rust: gpio: Add basic consumer abstractions

Quoted 9 lines · Kohei Ito

Add basic abstractions for GPIO consumer APIs.

Due to a bindgen issue that may generate the wrong type for enum types, gpio/consumer.h is included at the top of bindings_helper.h as a temporary workaround. Once the issue is resolved, it can be moved back to its proper alphabetical position.

---

My rust skills are still quite limited. This doesn't look bad but I'd also prefer someone more well versed have a look at tell me if these make sense.

Bartosz

#9 lore raw

Re: [PATCH 2/3] rust: gpio: Add basic consumer abstractions

In reply to Kohei Ito
Quoted 1 line · Kohei Ito

Add basic abstractions for GPIO consumer APIs.

Wow, GPIO! That brings some good memories back. :_)

Quoted 5 lines

Due to a bindgen issue that may generate the wrong type for enum types, gpio/consumer.h is included at the top of bindings_helper.h as a temporary workaround. Once the issue is resolved, it can be moved back to its proper alphabetical position.

Can you describe what the issue is, and share any relevant link?

Quoted 62 lines
---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/gpio.rs             |   2 +
 rust/kernel/gpio/consumer.rs    | 437 ++++++++++++++++++++++++++++++++++++++++
 3 files changed, 440 insertions(+)
rust/bindings/bindings_helper.h +1 -0
index 98b048b36771..30985c102c70 100644
@@ -26,6 +26,7 @@
  * This workaround may not be possible in some cases, depending on how the C
  * headers are set up.
  */
+#include <linux/gpio/consumer.h>
 #include <linux/hrtimer_types.h>
 
 #include <linux/acpi.h>
rust/kernel/gpio.rs +2 -0
index 819efc8a0c05..40b6c64e8f5e 100644
@@ -11,6 +11,8 @@
     prelude::*, //
 };
 
+pub mod consumer;
+
 /// Describes GPIO direction.
 #[derive(Clone, Copy, PartialEq, Eq)]
 #[repr(u32)]
rust/kernel/gpio/consumer.rs new file +22 -0
new file mode 100644
index 000000000000..f81c7381c075
@@ -0,0 +1,437 @@
+// SPDX-License-Identifier: GPL-2.0
+// This file is based on rust/kernel/clk.rs.
+
+//! GPIO consumer abstractions.
+//!
+//! C header: [`include/linux/gpio/consumer.h`](srctree/include/linux/gpio/consumer.h)
+//!
+//! Reference: <https://docs.kernel.org/driver-api/gpio/consumer.html>
+
+use crate::{
+    device::Device,
+    error::{
+        from_err_ptr,
+        to_result,
+        Error,
+        Result, //
+    },
+    gpio::{
+        LineDirection,
+        LogicalLineLevel,
+        PhysicalLineLevel, //
+    },

rust/kernel/gpio/consumer.rs line 32

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    prelude::*, //
+};
+
+use core::{ops::Deref, ptr};
+
+/// The GPIO descriptor flags to configure its direction and output value.
+///
+/// Rust abstraction for the C [`enum gpiod_flags`].
+///
+/// They can be combined with the operators `|`, and `&`.

The C comment for gpiod_flags says "these values cannot be OR'd" so I guess this comment isn't true. Besides, there is no BitOr impl for GpiodFlags in the patch so it actually cannot be done.

Quoted 24 lines
rust/kernel/gpio/consumer.rs new file +24 -0
+///
+/// Values can be used from the associated constants such as
+/// [`Flags::GPIOD_ASIS`].
+#[derive(Clone, Copy, PartialEq)]
+pub struct GpiodFlags(bindings::gpiod_flags);
+
+impl GpiodFlags {
+    /// Don't change anything.
+    pub const ASIS: Self = Self::new(bindings::gpiod_flags_GPIOD_ASIS);
+
+    /// Set lines to input mode.
+    pub const IN: Self = Self::new(bindings::gpiod_flags_GPIOD_IN);
+
+    /// Set lines to output and drive them low.
+    pub const OUT_LOW: Self = Self::new(bindings::gpiod_flags_GPIOD_OUT_LOW);
+
+    /// Set lines to output and drive them high.
+    pub const OUT_HIGH: Self = Self::new(bindings::gpiod_flags_GPIOD_OUT_HIGH);
+
+    /// Set lines to open-drain output and drive them low.
+    pub const OUT_LOW_OPEN_DRAIN: Self = Self::new(bindings::gpiod_flags_GPIOD_OUT_LOW_OPEN_DRAIN);
+
+    /// Set lines to open-drain output and drive them high.
+    pub const OUT_HIGH_OPEN_DRAIN: Self =

rust/kernel/gpio/consumer.rs line 66

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+        Self::new(bindings::gpiod_flags_GPIOD_OUT_HIGH_OPEN_DRAIN);
+
+    fn into_inner(self) -> bindings::gpiod_flags {
+        self.0
+    }
+
+    // Always inline to optimize out error path of `build_assert`.
+    #[inline(always)]
+    const fn new(value: bindings::gpiod_flags) -> Self {
+        build_assert!(value as u64 <= bindings::gpiod_flags::MAX as u64);

Better to not use build_assert here as it inserts build-time landmines.

Since you are only using this to build the constants above, you can just do Self(bindings::gpiod_flags_*) on them. Adding an extra assert for an bounded enum type doesn't add any extra protection.

rust/kernel/gpio/consumer.rs line 71

Quoted 5 lines
rust/kernel/gpio/consumer.rs new file +5 -0
+        Self(value)
+    }
+}
+
+/// A reference-counted gpio descriptor.

Not really - the GPIO device is reference-counted, but descriptors are not. Calling gpiod_get a second time returns EBUSY.

Quoted 7 lines
rust/kernel/gpio/consumer.rs new file +7 -0
+///
+/// Rust abstraction for the C [`struct gpio_desc`].
+///
+/// # Invariants
+///
+/// A [`GpioDesc`] instance holds either a pointer to a valid [`struct gpio_desc`] created by the C
+/// portion of the kernel or a `NULL` pointer.

rust/kernel/gpio/consumer.rs line 88

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+///
+/// Instances of this type are reference-counted. Calling [`GpioDesc::get`] ensures that the
+/// allocation remains valid for the lifetime of the [`GpioDesc`].
+///
+/// # Examples
+///
+/// The following example demonstrates how to obtain a GPIO line for a device.
+///
+/// ```
+/// use crate::{

These doctests won't compile as they are supposed to use kernel::, not crate::.

Please make sure to include the doctests when building (CONFIG_RUST_KERNEL_DOCTESTS build option), and to also build the rustdoc target as per the checklist [1].

[1] https://rust-for-linux.com/contributing#submit-checklist-addendum

Quoted 18 lines
rust/kernel/gpio/consumer.rs new file +18 -0
+///     device::Device,
+///     error::Result,
+///     gpio::{
+///         consumer::{
+///             GpioDesc,
+///             GpiodFlags, //
+///         },
+///         LogicalLineLevel, //
+///     }, //
+/// };
+///
+/// fn examine_gpio(dev: &Device) -> Result {
+///     let gpiod = GpioDesc::get(dev, Some(c"reset"), GpiodFlags::ASIS)?;
+///
+///     gpiod.set_value(LogicalLineLevel::Inactive)?;
+///
+///     gpiod.set_value(LogicalLineLevel::Active)?;
+///

rust/kernel/gpio/consumer.rs line 116

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+///     Ok(())
+/// }
+/// ```
+///
+/// [`struct gpio_desc`]: https://docs.kernel.org/driver-api/gpio/consumer.html
+#[repr(transparent)]
+pub struct GpioDesc(*mut bindings::gpio_desc);
+
+// SAFETY: It is safe to call `gpiod_put` on another thread than where `gpiod_get` was called.
+unsafe impl Send for GpioDesc {}

We should probably also implement Sync so GPIOs can be used in interrupt context.

rust/kernel/gpio/consumer.rs line 124

Quoted 8 lines
rust/kernel/gpio/consumer.rs new file +8 -0
+
+impl GpioDesc {
+    /// Gets [`GpioDesc`] corresponding to a [`Device`] and a connection id.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get`] API.
+    ///
+    /// [`gpiod_get`]: https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get
+    pub fn get(dev: &Device, name: Option<&CStr>, flags: GpiodFlags) -> Result<Self> {

dev here is only used as a lookup key, and the GPIO descriptor can outlive the device being unbound (the GPIO can actually even be obtained while the device is unbound!). This is because dev is not the provider of the GPIO, but as the API name implies its consumer - i.e. the device on which the GPIO is expected to have an effect.

This is what the GPIO API expects, but it looks a bit counterintuitive when compared to most other Rust subsystems, where an obtained resource is typically tied to the device given as parameter being bound. I think it's worth mentioning in the comment.

Quoted 23 lines
rust/kernel/gpio/consumer.rs new file +23 -0
+        let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
+
+        // SAFETY: It is safe to call [`gpiod_get`] for a valid device pointer.
+        //
+        // INVARIANT: The reference-count is decremented when [`GpioDesc`] goes out of scope.
+        Ok(Self(from_err_ptr(unsafe {
+            bindings::gpiod_get(dev.as_raw(), con_id, flags.into_inner())
+        })?))
+    }
+
+    /// Obtain the raw [`struct gpio_desc`] pointer.
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::gpio_desc {
+        self.0
+    }
+
+    /// Get the direction.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_direction`] API.
+    ///
+    /// [`gpiod_get_direction`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_direction
+    #[inline]

rust/kernel/gpio/consumer.rs line 157

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    pub fn get_direction(&self) -> Result<LineDirection> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_direction`].
+        let ret = unsafe { bindings::gpiod_get_direction(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            LineDirection::try_from(ret)
+        }
+    }

IIUC the direction of a GPIO at a given point in the code is always statically known, and only a subset of the API really make sense for a given direction (e.g. gpiod_set_raw_value_commit returns EPERM if the direction is not output). So this is a prime candidate for using the typestate pattern to store the direction in the type.

I.e. you would have GpioDesc<Input>, GpioDesc<Output>, and changing the direction would consume the descriptor and return the new one with the requested direction.

The regulator Rust API makes use of this pattern, you can check it out for an example if needed.

Quoted 107 lines
rust/kernel/gpio/consumer.rs new file +107 -0
+
+    /// Set the GPIO direction to input.
+    ///
+    /// Equivalent to the kernel's [`gpiod_direction_input`] API.
+    ///
+    /// [`gpiod_direction_input`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_direction_input
+    #[inline]
+    pub fn direction_input(&self) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_direction_input`].
+        to_result(unsafe { bindings::gpiod_direction_input(self.as_raw()) })
+    }
+
+    /// Set the GPIO direction to output and assign the logical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_direction_output`] API.
+    ///
+    /// [`gpiod_direction_output`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_direction_output
+    #[inline]
+    pub fn direction_output(&self, value: LogicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_direction_output`].
+        to_result(unsafe { bindings::gpiod_direction_output(self.as_raw(), value.as_c_int()) })
+    }
+
+    /// Set the GPIO direction to output and assign the physical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_direction_output_raw`] API.
+    ///
+    /// [`gpiod_direction_output_raw`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_direction_output_raw
+    #[inline]
+    pub fn direction_output_raw(&self, value: PhysicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_direction_output_raw`].
+        to_result(unsafe { bindings::gpiod_direction_output_raw(self.as_raw(), value.as_c_int()) })
+    }
+
+    /// Get the logical GPIO value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_value`] API.
+    ///
+    /// [`gpiod_get_value`]: https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_value
+    #[inline]
+    pub fn get_value(&self) -> Result<LogicalLineLevel> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_value`].
+        let ret = unsafe { bindings::gpiod_get_value(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            LogicalLineLevel::try_from(ret)
+        }
+    }
+
+    /// Assign the logical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_set_value`] API.
+    ///
+    /// [`gpiod_set_value`]: https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_set_value
+    #[inline]
+    pub fn set_value(&self, value: LogicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_set_value`].
+        to_result(unsafe { bindings::gpiod_set_value(self.as_raw(), value.as_c_int()) })
+    }
+
+    /// Get the physical GPIO value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_raw_value`] API.
+    ///
+    /// [`gpiod_get_raw_value`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_raw_value
+    #[inline]
+    pub fn get_raw_value(&self) -> Result<PhysicalLineLevel> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_raw_value`].
+        let ret = unsafe { bindings::gpiod_get_raw_value(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            PhysicalLineLevel::try_from(ret)
+        }
+    }
+
+    /// Assign the physical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_set_raw_value`] API.
+    ///
+    /// [`gpiod_set_raw_value`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_set_raw_value
+    #[inline]
+    pub fn set_raw_value(&self, value: PhysicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_set_raw_value`].
+        to_result(unsafe { bindings::gpiod_set_raw_value(self.as_raw(), value.as_c_int()) })
+    }
+
+    /// Get the logical GPIO value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_value_cansleep`] API.
+    ///
+    /// [`gpiod_get_value_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_value_cansleep
+    #[inline]

rust/kernel/gpio/consumer.rs line 274

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    pub fn get_value_cansleep(&self) -> Result<LogicalLineLevel> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_value_cansleep`].
+        let ret = unsafe { bindings::gpiod_get_value_cansleep(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            LogicalLineLevel::try_from(ret)
+        }
+    }

Here as well it would have been nice if we could avoid having _cansleep variants, but I am not sure there is anything we can do for that so I guess we'll need to keep all the variants.

Quoted 52 lines
rust/kernel/gpio/consumer.rs new file +52 -0
+
+    /// Assign the logical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_set_value_cansleep`] API.
+    ///
+    /// [`gpiod_set_value_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_set_value_cansleep
+    #[inline]
+    pub fn set_value_cansleep(&self, value: LogicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_set_value_cansleep`].
+        to_result(unsafe { bindings::gpiod_set_value_cansleep(self.as_raw(), value.as_c_int()) })
+    }
+
+    /// Get the physical GPIO value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_raw_value_cansleep`] API.
+    ///
+    /// [`gpiod_get_raw_value_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_raw_value_cansleep
+    #[inline]
+    pub fn get_raw_value_cansleep(&self) -> Result<PhysicalLineLevel> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_raw_value_cansleep`].
+        let ret = unsafe { bindings::gpiod_get_raw_value_cansleep(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            PhysicalLineLevel::try_from(ret)
+        }
+    }
+
+    /// Assign the physical value.
+    ///
+    /// Equivalent to the kernel's [`gpiod_set_raw_value_cansleep`] API.
+    ///
+    /// [`gpiod_set_raw_value_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_set_raw_value_cansleep
+    #[inline]
+    pub fn set_raw_value_cansleep(&self, value: PhysicalLineLevel) -> Result {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_set_raw_value_cansleep`].
+        to_result(unsafe {
+            bindings::gpiod_set_raw_value_cansleep(self.as_raw(), value.as_c_int())
+        })
+    }
+
+    /// Test whether the GPIO is active-low or not.
+    ///
+    /// Equivalent to the kernel's [`gpiod_is_active_low`] API.
+    ///
+    /// [`gpiod_is_active_low`]:

rust/kernel/gpio/consumer.rs line 336

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_is_active_low
+    #[inline]
+    pub fn is_active_low(&self) -> Result<bool> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_is_active_low`].
+        match unsafe { bindings::gpiod_is_active_low(self.as_raw()) } {
+            0 => Ok(false),
+            1 => Ok(true),
+            err => Err(Error::from_errno(err)),
+        }

In C this function cannot fail for a valid descriptor, so the Rust one shouldn't either. Anything != 0 can be considered true.

Quoted 8 lines
rust/kernel/gpio/consumer.rs new file +8 -0
+    }
+
+    /// Report whether gpio value access may sleep or not.
+    ///
+    /// Equivalent to the kernel's [`gpiod_cansleep`] API.
+    ///
+    /// [`gpiod_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_cansleep

rust/kernel/gpio/consumer.rs line 354

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    #[inline]
+    pub fn cansleep(&self) -> Result<bool> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_cansleep`].
+        match unsafe { bindings::gpiod_cansleep(self.as_raw()) } {
+            0 => Ok(false),
+            1 => Ok(true),
+            err => Err(Error::from_errno(err)),
+        }
+    }

Same here.

Also, as a general guideline, it is good to have a concrete user for new Rust abstractions. Do you have a project that will make use of this?

author
#10 lore raw

Re: [PATCH 2/3] rust: gpio: Add basic consumer abstractions

Hi Alexandre,

thank you for your review.

Quoted 6 lines
Quoted 4 lines

Due to a bindgen issue that may generate the wrong type for enum types, gpio/consumer.h is included at the top of bindings_helper.h as a temporary workaround. Once the issue is resolved, it can be moved back to its proper alphabetical position.

Can you describe what the issue is, and share any relevant link?

bindgen can generate the wrong type for the enums when their forward declarations appear before the actual definitions. The details are described in [1].

I haven't confirmed that gpiod_flags is actually affected. I placed the include at the top as a precaution, but if it isn't needed I'll drop the workaround.

[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=8cbc95f983bcec7e042266766ffe0d68980e4290

Quoted 9 lines

rust/kernel/gpio/consumer.rs line 32

Quoted 5 lines
rust/kernel/gpio/consumer.rs new file +5 -0
+/// The GPIO descriptor flags to configure its direction and output value.
+///
+/// Rust abstraction for the C [`enum gpiod_flags`].
+///
+/// They can be combined with the operators `|`, and `&`.

The C comment for gpiod_flags says "these values cannot be OR'd" so I guess this comment isn't true. Besides, there is no BitOr impl for GpiodFlags in the patch so it actually cannot be done.

Good catch! I'll correct it.

Quoted 11 lines

rust/kernel/gpio/consumer.rs line 66

Quoted 4 lines
rust/kernel/gpio/consumer.rs new file +4 -0
+    // Always inline to optimize out error path of `build_assert`.
+    #[inline(always)]
+    const fn new(value: bindings::gpiod_flags) -> Self {
+        build_assert!(value as u64 <= bindings::gpiod_flags::MAX as u64);

Better to not use build_assert here as it inserts build-time landmines.

Since you are only using this to build the constants above, you can just do Self(bindings::gpiod_flags_*) on them. Adding an extra assert for an bounded enum type doesn't add any extra protection.

Sure. I'll remove it.

Quoted 4 lines
Quoted 1 line

+/// A reference-counted gpio descriptor.

Not really - the GPIO device is reference-counted, but descriptors are not. Calling gpiod_get a second time returns EBUSY.

Sure. I'll correct it.

Quoted 11 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+/// ```
+/// use crate::{

These doctests won't compile as they are supposed to use kernel::, not crate::.

Please make sure to include the doctests when building (CONFIG_RUST_KERNEL_DOCTESTS build option), and to also build the rustdoc target as per the checklist [1].

[1] https://rust-for-linux.com/contributing#submit-checklist-addendum

Sure. I'll fix it and make sure to run the doctests and build rustdoc.

Quoted 5 lines

rust/kernel/gpio/consumer.rs line 116

Quoted 2 lines
rust/kernel/gpio/consumer.rs new file +2 -0
+// SAFETY: It is safe to call `gpiod_put` on another thread than where `gpiod_get` was called.
+unsafe impl Send for GpioDesc {}

We should probably also implement Sync so GPIOs can be used in interrupt context.

I agree we want Sync so that GPIOs can be used from interrupt context. However, the direction setters are not safe to call concurrently on the same descriptor: gpiolib changes the hardware direction and then updates GPIOD_FLAG_IS_OUT, so the two can become inconsistent.

I think we can add Sync if the direction setters take &mut self (or use the typestate approach). I'll look into this together with the typestate design.

Quoted 15 lines

rust/kernel/gpio/consumer.rs line 124

Quoted 8 lines
rust/kernel/gpio/consumer.rs new file +8 -0
+
+impl GpioDesc {
+    /// Gets [`GpioDesc`] corresponding to a [`Device`] and a connection id.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get`] API.
+    ///
+    /// [`gpiod_get`]: https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get
+    pub fn get(dev: &Device, name: Option<&CStr>, flags: GpiodFlags) -> Result<Self> {

dev here is only used as a lookup key, and the GPIO descriptor can outlive the device being unbound (the GPIO can actually even be obtained while the device is unbound!). This is because dev is not the provider of the GPIO, but as the API name implies its consumer - i.e. the device on which the GPIO is expected to have an effect.

Quoted 4 lines

This is what the GPIO API expects, but it looks a bit counterintuitive when compared to most other Rust subsystems, where an obtained resource is typically tied to the device given as parameter being bound. I think it's worth mentioning in the comment.

Sure. I'll add a note explaining how dev is used.

Quoted 24 lines
Quoted 7 lines
rust/kernel/gpio/consumer.rs new file +7 -0
+    /// Get the direction.
+    ///
+    /// Equivalent to the kernel's [`gpiod_get_direction`] API.
+    ///
+    /// [`gpiod_get_direction`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_get_direction
+    #[inline]

rust/kernel/gpio/consumer.rs line 157

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    pub fn get_direction(&self) -> Result<LineDirection> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_get_direction`].
+        let ret = unsafe { bindings::gpiod_get_direction(self.as_raw()) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            LineDirection::try_from(ret)
+        }
+    }

IIUC the direction of a GPIO at a given point in the code is always statically known, and only a subset of the API really make sense for a given direction (e.g. gpiod_set_raw_value_commit returns EPERM if the direction is not output). So this is a prime candidate for using the typestate pattern to store the direction in the type.

Quoted 6 lines

I.e. you would have GpioDesc<Input>, GpioDesc<Output>, and changing the direction would consume the descriptor and return the new one with the requested direction.

The regulator Rust API makes use of this pattern, you can check it out for an example if needed.

I haven't fully grasped the idea yet. I'll check the regulator Rust API implementation and explore a typestate implementation for GPIO consumer APIs.

Quoted 16 lines
Quoted 5 lines
rust/kernel/gpio/consumer.rs new file +5 -0
+    /// Test whether the GPIO is active-low or not.
+    ///
+    /// Equivalent to the kernel's [`gpiod_is_active_low`] API.
+    ///
+    /// [`gpiod_is_active_low`]:

rust/kernel/gpio/consumer.rs line 336

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_is_active_low
+    #[inline]
+    pub fn is_active_low(&self) -> Result<bool> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_is_active_low`].
+        match unsafe { bindings::gpiod_is_active_low(self.as_raw()) } {
+            0 => Ok(false),
+            1 => Ok(true),
+            err => Err(Error::from_errno(err)),
+        }
Quoted 2 lines

In C this function cannot fail for a valid descriptor, so the Rust one shouldn't either. Anything != 0 can be considered true.

Sure. I'll correct it for GpioDesc. Should we return Result<bool> for OptionalGpioDesc? As I understand, NULL GPIO descriptors can't return the right state.

Quoted 17 lines
Quoted 6 lines
rust/kernel/gpio/consumer.rs new file +6 -0
+    /// Report whether gpio value access may sleep or not.
+    ///
+    /// Equivalent to the kernel's [`gpiod_cansleep`] API.
+    ///
+    /// [`gpiod_cansleep`]:
+    /// https://docs.kernel.org/driver-api/gpio/index.html#c.gpiod_cansleep

rust/kernel/gpio/consumer.rs line 354

Quoted 10 lines
rust/kernel/gpio/consumer.rs new file +10 -0
+    #[inline]
+    pub fn cansleep(&self) -> Result<bool> {
+        // SAFETY: By the type invariants, self.as_raw() is a valid argument for
+        // [`gpiod_cansleep`].
+        match unsafe { bindings::gpiod_cansleep(self.as_raw()) } {
+            0 => Ok(false),
+            1 => Ok(true),
+            err => Err(Error::from_errno(err)),
+        }
+    }
Quoted 1 line

Same here.

Sure. I'll fix it in the same way.

Quoted 2 lines

Also, as a general guideline, it is good to have a concrete user for new Rust abstractions. Do you have a project that will make use of this?

No, I don't have a specific project that will use this. My motivation is that Rust drivers currently have no way to use GPIO lines, so I expect that providing a basic set of consumer APIs would make it easier for such drivers to appear.

That said, I understand the concern about adding APIs without actual users. If you think it should wait until there is a concrete user, please let me know.

Best regards,
Kohei Ito

author
#11 lore raw

PATCH 3/3 sample: rust: Add GPIO consumer sample driver

In reply to Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---
 samples/rust/Kconfig               |  11 +++
 samples/rust/Makefile              |   1 +
 samples/rust/rust_gpio_consumer.rs | 156 +++++++++++++++++++++++++++++++++++++
 3 files changed, 168 insertions(+)
samples/rust/Kconfig +11 -0
index c49ab9106345..1085d90c87f3 100644
@@ -161,6 +161,17 @@ config SAMPLE_RUST_DRIVER_AUXILIARY
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_GPIO_CONSUMER
+	tristate "GPIO Consumer Driver"
+	depends on GPIOLIB
+	help
+	  This option builds the Rust GPIO consumer sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_gpio_consumer.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_SOC
 	tristate "SoC Driver"
 	select SOC_BUS
samples/rust/Makefile +1 -0
index 6c0aaa58cccc..1cf181dea6d3 100644
@@ -15,6 +15,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_USB)		+= rust_driver_usb.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
 obj-$(CONFIG_SAMPLE_RUST_CONFIGFS)		+= rust_configfs.o
+obj-$(CONFIG_SAMPLE_RUST_GPIO_CONSUMER)		+= rust_gpio_consumer.o
 obj-$(CONFIG_SAMPLE_RUST_SOC)			+= rust_soc.o
 
 rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/rust_gpio_consumer.rs new file +156 -0

156 lines not on this page · raw message

Signature · 1 line
2.50.1
#12 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Bartosz

author
#13 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

Best regards,
Kohei Ito

#14 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Quoted 21 lines · Kohei Ito

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

Quoted 6 lines

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

The problem is that this sample driver never probes, so in effect it is only ever compile-tested. Without support for the provider API, you need to include a small C fixture providing a GPIO chip for it to be actually runtime-tested.

Doing the same using KUnit would involve building the gpio_chip using a bunch of unsafe statements working with the C bindings (which would then in turn require gpio/driver.h to be added), so I guess we'll want to wait until we have a proper Rust provider API to go that direction.

But if we add a sample driver, we need to make sure it is exercised.

#15 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Quoted 34 lines · Alexandre Courbot
Quoted 21 lines · Kohei Ito

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

Quoted 6 lines

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

The problem is that this sample driver never probes, so in effect it is only ever compile-tested. Without support for the provider API, you need to include a small C fixture providing a GPIO chip for it to be actually runtime-tested.

Quoted 5 lines

Doing the same using KUnit would involve building the gpio_chip using a bunch of unsafe statements working with the C bindings (which would then in turn require gpio/driver.h to be added), so I guess we'll want to wait until we have a proper Rust provider API to go that direction.

No, I was thinking about the gpio-sim module which is implemented as a platform driver which you can describe with a software node and then register to create a simulated GPIO provider against which the consumer APIs in rust could be tested.

To that end, we'd need to just register a platform device from rust and AFAICT, there are already APIs for that, except for the software nodes.

Bart

author
#16 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Hi Bartosz, Alexandre,

Thanks both for the feedback.

Quoted 47 lines · Bartosz Golaszewski
Quoted 34 lines · Alexandre Courbot
Quoted 21 lines · Kohei Ito

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

Quoted 6 lines

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

The problem is that this sample driver never probes, so in effect it is only ever compile-tested. Without support for the provider API, you need to include a small C fixture providing a GPIO chip for it to be actually runtime-tested.

Quoted 5 lines

Doing the same using KUnit would involve building the gpio_chip using a bunch of unsafe statements working with the C bindings (which would then in turn require gpio/driver.h to be added), so I guess we'll want to wait until we have a proper Rust provider API to go that direction.

No, I was thinking about the gpio-sim module which is implemented as a platform driver which you can describe with a software node and then register to create a simulated GPIO provider against which the consumer APIs in rust could be tested.

Quoted 4 lines

To that end, we'd need to just register a platform device from rust and AFAICT, there are already APIs for that, except for the software nodes.

Bart

I looked into this further, but couldn't find any Rust abstraction for registering a new platform_device (no file contains a platform device registration function such as platform_device_register(), platform_device_register_*(), or platform_device_alloc()/ platform_device_add()). So, we can't write a fully Rust kunit module for the GPIO consumer API, at least for v7.3-rc3.

The best approach I think is a combination of a Rust consumer driver and a C kunit module dedicated to testing the consumer driver. This is almost the same as drivers/gpio/gpiolib-kunit.c, except that instead of directly exercising the GPIO consumer APIs, the module I'm suggesting exercises them indirectly, through the Rust consumer driver.

Best regards,
Kohei Ito

#17 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Quoted 55 lines · Kohei Ito

Hi Bartosz, Alexandre,

Thanks both for the feedback.

Quoted 50 lines · Bartosz Golaszewski
Quoted 34 lines · Alexandre Courbot
Quoted 21 lines · Kohei Ito

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

Quoted 6 lines

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

The problem is that this sample driver never probes, so in effect it is only ever compile-tested. Without support for the provider API, you need to include a small C fixture providing a GPIO chip for it to be actually runtime-tested.

Quoted 5 lines

Doing the same using KUnit would involve building the gpio_chip using a bunch of unsafe statements working with the C bindings (which would then in turn require gpio/driver.h to be added), so I guess we'll want to wait until we have a proper Rust provider API to go that direction.

No, I was thinking about the gpio-sim module which is implemented as a platform driver which you can describe with a software node and then register to create a simulated GPIO provider against which the consumer APIs in rust could be tested.

To that end, we'd need to just register a platform device from rust and AFAICT, there are already APIs for that, except for the software nodes.

Quoted 9 lines
Quoted 1 line

Bart

I looked into this further, but couldn't find any Rust abstraction for registering a new platform_device (no file contains a platform device registration function such as platform_device_register(), platform_device_register_*(), or platform_device_alloc()/ platform_device_add()). So, we can't write a fully Rust kunit module for the GPIO consumer API, at least for v7.3-rc3.

Right, I must have misremembered this.

Quoted 6 lines

The best approach I think is a combination of a Rust consumer driver and a C kunit module dedicated to testing the consumer driver. This is almost the same as drivers/gpio/gpiolib-kunit.c, except that instead of directly exercising the GPIO consumer APIs, the module I'm suggesting exercises them indirectly, through the Rust consumer driver.

Can't you just call a C function registering the platform device from unsafe rust?

Bart

#18 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Quoted 75 lines · Bartosz Golaszewski
Quoted 55 lines · Kohei Ito

Hi Bartosz, Alexandre,

Thanks both for the feedback.

Quoted 50 lines · Bartosz Golaszewski
Quoted 34 lines · Alexandre Courbot
Quoted 21 lines · Kohei Ito

Hi, Bartosz,

Quoted 11 lines · Bartosz Golaszewski
Quoted 4 lines · Kohei Ito

Add a sample driver to demonstrate the use of the Rust GPIO APIs.

---

I don't like samples as they rarely get built or tested. We seem to already have kunit support for rust, wouldn't it make more sense to implement a kunit module for rust GPIO abstractions? If we don't have provider abstractions, you should be able to reuse gpio-sim as the GPIO controller for testing just by instantiating simulated GPIO devices.

Thank you for your suggestion.

I assume the kunit module you have in mind would be implemented like gpiolib-kunit.c. Based on your comment, I agree that a kunit-based approach is more appropriate than a sample driver.

Quoted 6 lines

However, as far as I know, we don't yet have Rust abstractions for platform_device registration and software_node, which are required to implement a kunit-based module for testing GPIO consumer APIs. Given the current state of Rust for Linux, I think creating a sample driver is a more practical approach for now. I would like to consider migrating to a kunit-based module as future work.

The problem is that this sample driver never probes, so in effect it is only ever compile-tested. Without support for the provider API, you need to include a small C fixture providing a GPIO chip for it to be actually runtime-tested.

Quoted 5 lines

Doing the same using KUnit would involve building the gpio_chip using a bunch of unsafe statements working with the C bindings (which would then in turn require gpio/driver.h to be added), so I guess we'll want to wait until we have a proper Rust provider API to go that direction.

No, I was thinking about the gpio-sim module which is implemented as a platform driver which you can describe with a software node and then register to create a simulated GPIO provider against which the consumer APIs in rust could be tested.

To that end, we'd need to just register a platform device from rust and AFAICT, there are already APIs for that, except for the software nodes.

Quoted 9 lines
Quoted 1 line

Bart

I looked into this further, but couldn't find any Rust abstraction for registering a new platform_device (no file contains a platform device registration function such as platform_device_register(), platform_device_register_*(), or platform_device_alloc()/ platform_device_add()). So, we can't write a fully Rust kunit module for the GPIO consumer API, at least for v7.3-rc3.

Right, I must have misremembered this.

Quoted 6 lines

The best approach I think is a combination of a Rust consumer driver and a C kunit module dedicated to testing the consumer driver. This is almost the same as drivers/gpio/gpiolib-kunit.c, except that instead of directly exercising the GPIO consumer APIs, the module I'm suggesting exercises them indirectly, through the Rust consumer driver.

Quoted 2 lines

Can't you just call a C function registering the platform device from unsafe rust?

You should be able to. It's a but laborious, but better than not having tests at all, and acceptable as a temporary solution IMHO.

Of course an even better solution would be to provide a safe abstraction for registering platform devices. :) I don't know exactly how much work that would be, but there is already a platform module, so supposedly we wouldn't be starting from absolute scratch.

author
#19 lore raw

Re: [PATCH 3/3] sample: rust: Add GPIO consumer sample driver

Hi Bartosz, Alexandre,

Thank you for your advice.

Quoted 10 lines
Quoted 9 lines
Quoted 6 lines

The best approach I think is a combination of a Rust consumer driver and a C kunit module dedicated to testing the consumer driver. This is almost the same as drivers/gpio/gpiolib-kunit.c, except that instead of directly exercising the GPIO consumer APIs, the module I'm suggesting exercises them indirectly, through the Rust consumer driver.

Can't you just call a C function registering the platform device from unsafe rust?

Quoted 7 lines

You should be able to. It's a but laborious, but better than not having tests at all, and acceptable as a temporary solution IMHO.

Of course an even better solution would be to provide a safe abstraction for registering platform devices. :) I don't know exactly how much work that would be, but there is already a platform module, so supposedly we wouldn't be starting from absolute scratch.

Sure. I'll explore the Rust kunit approach by directly calling C functions to register platform_device and software_node from unsafe Rust. I'll also drop the sample driver. I'll let you know if I face problems.

Best regards,
Kohei Ito