Skip to contentSkip to conversation

iio: position: add Rust driver for ams AS5600

RFC PATCH Superseded Muchamad Coirul Anwar 3 participants 13 messages Oct 16 – Nov 11

Subsystems (6)

v6 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

v6 cover iio: position: add Rust driver for ams AS5600

Add a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor.

The series adds generic fallible I/O support, SMBus access, a minimal read-only Rust IIO abstraction, and the AS5600 driver. The driver exposes raw angle and scale through IIO sysfs.

Reviews of the lifetime, concurrency, and teardown contracts in the Rust I2C and IIO abstractions would be especially helpful. Danilo and Igor, if you have time, I would appreciate your help reviewing those parts.

The Region-based view models byte-addressed registers and is not a general model for command-indexed 16-bit registers. The standalone word-read helpers accept any SMBus command byte.

The current interface is intentionally limited while a Rust regmap abstraction is unavailable. Feedback on whether this is an appropriate interim approach, or whether the work should wait for regmap, would be appreciated.

This series is based on commit 3fadfb9362cf
("rust: firmware: avoid UB in example by passing parameter"), which contains Gary Guo's io_projection-v6 infrastructure. It also depends on rust-next commit b93fb6e76ec1
("rust: error: add remaining error codes") for ENODATA; that commit is not included in this series.

Previous version:

https://lore.kernel.org/linux-iio/[email protected]/

Changes since RFC v5:

- Split FallibleIoCapable and the generic fallible try_* routing into a prerequisite patch.
- Require CONFIG_I2C=y because kernel::i2c is currently exported only when I2C is built in.
- Keep a bound parent borrow in the unregistered IIO builder and transfer registration ownership to parent devres.
- Derive the bound I2C client from the parent during read_raw instead of storing an ARef<I2cClient<Bound>> in the driver.
- Make IioDriver unsafe and document the validity requirements for raw channel specifications and the unsupported channel features.
- Reject operating modes other than INDIO_DIRECT_MODE.
- Use the external error-code dependency for ENODATA instead of adding the error code in this series.
- Clarify the writable-storage contract for read_raw output pointers.
- Replace the stale datasheet URL with the stable document identifier.

---

Testing:

Built for ARM with Rust enabled, I2C built in, and AS5600 built as a module. Tested on a BeagleBone Black with an AS5600 on i2c-2 at 0x36, running kernel 7.2.0-rc1-as5600-debug+.

Raw angle and scale reads passed with the magnet detected. With the magnet-detected bit clear, 10 consecutive reads returned ENODATA. I2C transport errors were propagated during a physical bus disconnect, and reads recovered after reconnection.

Concurrency testing used 10 parallel readers and repeated reads during 20 bind/unbind cycles. Lifecycle testing covered 50 bind/unbind cycles, 50 module load/unload cycles, module removal during active reads, module removal with an open sysfs file descriptor, and module removal while the I2C bus was in an error state.

KFENCE, UBSAN, lockdep, and kmemleak reported no issues. KASAN was not enabled because 32-bit ARM currently selects HAVE_RUST only when KASAN is disabled.

Muchamad Coirul Anwar (4):
rust: io: add FallibleIoCapable
i2c: rust: implement SMBus access via IoBackend
rust: add minimal IIO subsystem abstractions
iio: position: add Rust driver for ams AS5600

 drivers/iio/position/Kconfig    |  11 +
 drivers/iio/position/Makefile   |   1 +
 drivers/iio/position/as5600.rs  | 177 ++++++++++++
 include/linux/iio/iio.h         |   6 +-
 rust/bindings/bindings_helper.h |   2 +
 rust/kernel/bits.rs             |  29 ++
 rust/kernel/i2c.rs              | 248 +++++++++++++++++
 rust/kernel/iio.rs              | 480 ++++++++++++++++++++++++++++++++
 rust/kernel/io.rs               |  66 +++--
 rust/kernel/lib.rs              |   2 +
 10 files changed, 1000 insertions(+), 22 deletions(-)
 create mode 100644 drivers/iio/position/as5600.rs
 create mode 100644 rust/kernel/iio.rs
Signature · 1 line
2.50.0
#1 lore raw

RFC PATCH v6 1/4 rust: io: add FallibleIoCapable

Add a fallible I/O capability for backends whose accesses may fail independently of address validation.

Route try_read, try_write, try_write_reg, and try_update through the fallible capability. Provide a blanket implementation for infallible IoCapable backends so existing users retain their current behavior.

This allows transport-backed implementations such as I2C to expose only fallible access while keeping infallible operations unavailable.

---
 rust/kernel/io.rs | 66 +++++++++++++++++++++++++++++++++--------------
 1 file changed, 46 insertions(+), 20 deletions(-)
rust/kernel/io.rs +46 -20
index 95f46bb75f9e..516895ca2082 100644
@@ -276,6 +276,36 @@ pub trait IoCapable<T>: IoBackend {
     fn io_write<'a>(view: Self::View<'a, T>, value: T);
 }
 
+/// Fallible counterpart of [`IoCapable`] for I/O backends where operations can fail at the
+/// transport level (e.g. I2C, SPI).
+///
+/// Infallible backends ([`IoCapable`] implementors) get this for free via blanket implementation.
+/// Fallible-only backends implement this trait directly without implementing [`IoCapable`]; the
+/// infallible [`Io::read`], [`Io::write`], and [`Io::update`] methods will then be unavailable,
+/// enforcing that callers use the `try_*` variants instead.
+pub trait FallibleIoCapable<T>: IoBackend {
+    /// Performs an I/O read of type `T` at `view` and returns the result, or an error if the
+    /// transport-level operation fails.
+    fn io_try_read<'a>(view: Self::View<'a, T>) -> Result<T>;
+
+    /// Performs an I/O write of `value` at `view`, or returns an error if the transport-level
+    /// operation fails.
+    fn io_try_write<'a>(view: Self::View<'a, T>, value: T) -> Result;
+}
+
+impl<B: IoCapable<T>, T> FallibleIoCapable<T> for B {
+    #[inline(always)]
+    fn io_try_read<'a>(view: Self::View<'a, T>) -> Result<T> {
+        Ok(Self::io_read(view))
+    }
+
+    #[inline(always)]
+    fn io_try_write<'a>(view: Self::View<'a, T>, value: T) -> Result {
+        Self::io_write(view, value);
+        Ok(())
+    }
+}
+
 /// Trait indicating that an I/O backend supports memory copy operations.
 pub trait IoCopyable: IoBackend {
     /// Copy contents of `view` to `buffer`.
@@ -645,7 +675,7 @@ fn copy_to_slice(self, data: &mut [u8])
     fn try_read8(self, offset: usize) -> Result<u8>
     where
         usize: IoLoc<Self::Target, u8, IoType = u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_read(offset)
     }
@@ -655,7 +685,7 @@ fn try_read8(self, offset: usize) -> Result<u8>
     fn try_read16(self, offset: usize) -> Result<u16>
     where
         usize: IoLoc<Self::Target, u16, IoType = u16>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_read(offset)
     }
@@ -665,7 +695,7 @@ fn try_read16(self, offset: usize) -> Result<u16>
     fn try_read32(self, offset: usize) -> Result<u32>
     where
         usize: IoLoc<Self::Target, u32, IoType = u32>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_read(offset)
     }
@@ -675,7 +705,7 @@ fn try_read32(self, offset: usize) -> Result<u32>
     fn try_read64(self, offset: usize) -> Result<u64>
     where
         usize: IoLoc<Self::Target, u64, IoType = u64>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_read(offset)
     }
@@ -685,7 +715,7 @@ fn try_read64(self, offset: usize) -> Result<u64>
     fn try_write8(self, value: u8, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u8, IoType = u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_write(offset, value)
     }
@@ -695,7 +725,7 @@ fn try_write8(self, value: u8, offset: usize) -> Result
     fn try_write16(self, value: u16, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u16, IoType = u16>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_write(offset, value)
     }
@@ -705,7 +735,7 @@ fn try_write16(self, value: u16, offset: usize) -> Result
     fn try_write32(self, value: u32, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u32, IoType = u32>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_write(offset, value)
     }
@@ -715,7 +745,7 @@ fn try_write32(self, value: u32, offset: usize) -> Result
     fn try_write64(self, value: u64, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u64, IoType = u64>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_write(offset, value)
     }
@@ -827,10 +857,10 @@ fn write64(self, value: u64, offset: usize)
     fn try_read<T, L>(self, location: L) -> Result<T>
     where
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<L::IoType>,
+        Self::Backend: FallibleIoCapable<L::IoType>,
     {
         let view = io_view::<Self, L::IoType>(self, location.offset())?;
-        Ok(Self::Backend::io_read(view).into())
+        Ok(Self::Backend::io_try_read(view)?.into())
     }
 
     /// Generic fallible write with runtime bounds check.
@@ -860,12 +890,11 @@ fn try_read<T, L>(self, location: L) -> Result<T>
     fn try_write<T, L>(self, location: L, value: T) -> Result
     where
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<L::IoType>,
+        Self::Backend: FallibleIoCapable<L::IoType>,
     {
         let view = io_view::<Self, L::IoType>(self, location.offset())?;
         let io_value = value.into();
-        Self::Backend::io_write(view, io_value);
-        Ok(())
+        Self::Backend::io_try_write(view, io_value)
     }
 
     /// Generic fallible write of a fully-located register value.
@@ -905,7 +934,7 @@ fn try_write_reg<T, L, V>(self, value: V) -> Result
     where
         L: IoLoc<Self::Target, T>,
         V: LocatedRegister<Self::Target, Location = L, Value = T>,
-        Self::Backend: IoCapable<L::IoType>,
+        Self::Backend: FallibleIoCapable<L::IoType>,
     {
         let (location, value) = value.into_io_op();
 
@@ -938,16 +967,13 @@ fn try_write_reg<T, L, V>(self, value: V) -> Result
     fn try_update<T, L, F>(self, location: L, f: F) -> Result
     where
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<L::IoType>,
+        Self::Backend: FallibleIoCapable<L::IoType>,
         F: FnOnce(T) -> T,
     {
         let view = io_view::<Self, L::IoType>(self, location.offset())?;
-
-        let value: T = Self::Backend::io_read(view).into();
+        let value: T = Self::Backend::io_try_read(view)?.into();
         let io_value = f(value).into();
-        Self::Backend::io_write(view, io_value);
-
-        Ok(())
+        Self::Backend::io_try_write(view, io_value)
     }
 
     /// Generic infallible read with compile-time bounds check.
Signature · 1 line
2.50.0
#2 lore raw

RFC PATCH v6 2/4 i2c: rust: implement SMBus access via IoBackend

In reply to Muchamad Coirul Anwar

Implement fallible SMBus byte and word access for bound I2C clients using the generic I/O backend infrastructure.

I2C transactions may fail due to NACK, arbitration loss, or timeout, so use FallibleIoCapable rather than the infallible IoCapable interface. Propagate errors returned by the I2C core to callers.

Provide smbus_io() for byte-addressed register access and standalone word helpers for devices whose word register starts at an odd offset. Also provide smbus_read_word_swapped() for devices storing the high byte at the first register address.

Restrict these operations to I2cClient<Bound>, ensuring that bus I/O is only available while the client remains bound.

---
 rust/kernel/i2c.rs | 248 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 248 insertions(+)
rust/kernel/i2c.rs +248 -0
index 624b971ca8b0..a53f7ee42b13 100644
@@ -14,8 +14,15 @@
     devres::Devres,
     driver,
     error::*,
+    io::{
+        FallibleIoCapable,
+        IoBackend,
+        IoBase,
+        Region, //
+    },
     of,
     prelude::*,
+    ptr::KnownSize,
     sync::aref::{
         ARef,
         AlwaysRefCounted, //
@@ -601,3 +608,244 @@ unsafe impl Send for Registration {}
 // SAFETY: `Registration` offers no interior mutability (no mutation through &self
 // and no mutable access is exposed)
 unsafe impl Sync for Registration {}
+
+/// I/O backend for SMBus register access via I2C.
+///
+/// This backend implements only [`FallibleIoCapable`] and not
+/// [`crate::io::IoCapable`], because I2C/SMBus transactions can fail
+/// regardless of address validity. The infallible [`crate::io::Io::read`],
+/// [`crate::io::Io::write`], and [`crate::io::Io::update`] methods are
+/// therefore unavailable for this backend.
+pub struct I2cBackend;
+
+/// An SMBus view associated with a bound I2C client.
+///
+/// The pointer encodes a command offset and is never dereferenced as
+/// memory. Its type and, for dynamically sized targets, metadata describe
+/// the extent of the view.
+///
+/// # Invariants
+///
+/// The view is derived from the client's SMBus command region.
+/// Projections preserve the bounds of the source view.
+/// `client` remains valid and bound for the lifetime of the view.
+pub struct I2cView<'a, T: ?Sized> {
+    client: &'a I2cClient<device::Bound>,
+    ptr: *mut T,
+}
+
+impl<T: ?Sized> Copy for I2cView<'_, T> {}
+
+impl<T: ?Sized> Clone for I2cView<'_, T> {
+    #[inline]
+    fn clone(&self) -> Self {
+        *self
+    }
+}
+
+impl IoBackend for I2cBackend {
+    type View<'a, T: ?Sized + KnownSize> = I2cView<'a, T>;
+
+    #[inline]
+    fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut T {
+        view.ptr
+    }
+
+    #[inline]
+    unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSize>(
+        view: Self::View<'a, T>,
+        ptr: *mut U,
+    ) -> Self::View<'a, U> {
+        // INVARIANT: Per safety requirement.
+        I2cView {
+            client: view.client,
+            ptr,
+        }
+    }
+}
+
+impl FallibleIoCapable<u8> for I2cBackend {
+    #[inline]
+    fn io_try_read<'a>(view: I2cView<'a, u8>) -> Result<u8> {
+        // `io_view()` ensures `offset + 1 <= 256`, so `addr()` is at most 255;
+        // the `as u8` cast below is therefore lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+
+        // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_read_byte_data` is safe to call with any valid client pointer
+        // and any u8 command byte.
+        let ret = unsafe { bindings::i2c_smbus_read_byte_data(view.client.as_raw(), reg) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            Ok(ret as u8)
+        }
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result {
+        // `io_view()` ensures `offset + 1 <= 256`, so `addr()` is at most 255;
+        // the `as u8` cast below is therefore lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+
+        // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_byte_data` is safe to call with any valid client pointer
+        // and any u8 command byte and value.
+        let ret = unsafe { bindings::i2c_smbus_write_byte_data(view.client.as_raw(), reg, value) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            Ok(())
+        }
+    }
+}
+
+/// The `Region<256>` view is byte-addressed. Consequently, its generic
+/// 16-bit operations reject odd command bytes and command byte `0xFF`.
+/// Devices whose command bytes each select an independent 16-bit register
+/// should use [`I2cClient::smbus_read_word`] or
+/// [`I2cClient::smbus_read_word_swapped`] directly.
+impl FallibleIoCapable<u16> for I2cBackend {
+    #[inline]
+    fn io_try_read<'a>(view: I2cView<'a, u16>) -> Result<u16> {
+        // `io_view()` ensures `offset + 2 <= 256`, so `addr()` is at most 254;
+        // the `as u8` cast below is therefore lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+
+        // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_read_word_data` is safe to call with any valid client pointer
+        // and any u8 command byte.
+        let ret = unsafe { bindings::i2c_smbus_read_word_data(view.client.as_raw(), reg) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            Ok(ret as u16)
+        }
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u16>, value: u16) -> Result {
+        // `io_view()` ensures `offset + 2 <= 256`, so `addr()` is at most 254;
+        // the `as u8` cast below is therefore lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+
+        // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_word_data` is safe to call with any valid client pointer
+        // and any u8 command byte and u16 value.
+        let ret = unsafe { bindings::i2c_smbus_write_word_data(view.client.as_raw(), reg, value) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            Ok(())
+        }
+    }
+}
+
+impl<'a, T: ?Sized + KnownSize> IoBase<'a> for I2cView<'a, T> {
+    type Backend = I2cBackend;
+    type Target = T;
+
+    #[inline]
+    fn as_view(self) -> I2cView<'a, T> {
+        self
+    }
+}
+
+// SAFETY: The bound client borrow remains valid when the view is moved
+// between threads. The view exposes only SMBus transactions, which use
+// the I2C core's bus locking, and pointer projections that never
+// dereference the encoded address as memory. `T: Sync` preserves the
+// shared-view restriction.
+unsafe impl<T: ?Sized + Sync> Send for I2cView<'_, T> {}
+
+// SAFETY: Sharing a view permits concurrent SMBus transactions, which
+// use the I2C core's bus locking. The bound client remains valid for
+// the view's lifetime, and the encoded pointer is never dereferenced
+// as memory. `T: Sync` preserves the shared-view restriction.
+unsafe impl<T: ?Sized + Sync> Sync for I2cView<'_, T> {}
+
+impl I2cClient<device::Bound> {
+    /// Returns an I/O handle for SMBus register access on this I2C client.
+    ///
+    /// The returned handle provides fallible read and write methods for the
+    /// SMBus command byte range (0x00–0xFF). A command byte is a data byte which
+    /// often selects a register on the device. The 7-bit device address is handled
+    /// separately by the I2C core.
+    ///
+    /// [`crate::io::Io::try_read16`] and
+    /// [`crate::io::Io::try_write16`] on the returned handle reject
+    /// odd offsets because the [`Region`]-based bounds check requires
+    /// `offset % 2 == 0`. This model does not cover every SMBus register layout,
+    /// including layouts where auto-increment or auto-decrement results in command
+    /// bytes that appear unaligned. Use [`Self::smbus_read_word`] or
+    /// [`Self::smbus_read_word_swapped`] for word access at an odd command byte.
+    #[inline]
+    pub fn smbus_io(&self) -> I2cView<'_, Region<256>> {
+        // INVARIANT: The view borrows this bound client and covers the 256-byte
+        // SMBus command region.
+        //
+        // The provenance-free pointer encodes a command offset rather than a
+        // memory address. Its initial address is zero, and the region metadata
+        // supplies the length used for bounds checks. Projections select command
+        // offsets; SMBus accessors extract those offsets without dereferencing
+        // the pointer.
+        I2cView {
+            client: self,
+            ptr: Region::<256>::ptr_from_raw_parts_mut(core::ptr::without_provenance_mut(0), 256),
+        }
+    }
+
+    /// Reads the 16-bit SMBus word value returned for a command.
+    ///
+    /// Wraps `i2c_smbus_read_word_data`. The `reg` parameter is the SMBus
+    /// command byte (0x00–0xFF), a data byte which often selects a register on
+    /// the device. SMBus transmits the low byte first.
+    ///
+    /// Use [`Self::smbus_read_word_swapped`] for devices that transmit the
+    /// high byte of a multi-byte value first.
+    ///
+    /// Returns `Err` if the bus transaction fails, for example because of a
+    /// NACK, arbitration loss, or timeout.
+    #[inline]
+    pub fn smbus_read_word(&self, reg: u8) -> Result<u16> {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_read_word_data` is safe to call with any valid client
+        // pointer and any u8 command byte.
+        let ret = unsafe { bindings::i2c_smbus_read_word_data(self.as_raw(), reg) };
+        if ret < 0 {
+            Err(Error::from_errno(ret))
+        } else {
+            Ok(ret as u16)
+        }
+    }
+
+    /// Reads a 16-bit word from an SMBus command and swaps its two bytes.
+    ///
+    /// Wraps `i2c_smbus_read_word_data` and applies [`u16::swap_bytes`] to the
+    /// result. The `reg` parameter is the SMBus command byte (0x00–0xFF), a data
+    /// byte which often selects a register on the device.
+    ///
+    /// SMBus transmits the low byte first. This method swaps the returned bytes
+    /// for devices that transmit the high byte of a multi-byte value first.
+    ///
+    /// Returns `Err` if the bus transaction fails, for example because of a
+    /// NACK, arbitration loss, or timeout.
+    ///
+    /// # Example
+    ///
+    /// ```ignore
+    /// // AS5600 stores the 12-bit raw angle at command byte 0x0C with its
+    /// // high byte first.
+    /// let raw = client.smbus_read_word_swapped(0x0C)?;
+    /// let angle = raw & 0x0fff;
+    /// ```
+    #[inline]
+    pub fn smbus_read_word_swapped(&self, reg: u8) -> Result<u16> {
+        self.smbus_read_word(reg).map(u16::swap_bytes)
+    }
+}
Signature · 1 line
2.50.0
#3 lore raw

RFC PATCH v6 3/4 rust: add minimal IIO subsystem abstractions

In reply to Muchamad Coirul Anwar

Add minimal Rust abstractions needed to register direct-mode IIO devices exposing read_raw channel information.

Provide a type-safe IioChanInfo selector, IioVal return types, and an IioDriver trait. Add a C callback trampoline that validates the channel information selector, invokes the Rust driver, and converts IioVal into the representation expected by the IIO core.

Use typestate to distinguish unregistered and registered devices. The unregistered builder borrows the bound parent. After successful registration, transfer ownership to parent devres so that the IIO device is unregistered during parent resource teardown, before destroying the Rust private data and releasing the allocation reference.

Keep allocation and private-data destruction under Rust ownership; parent devres owns the registration wrapper rather than managing the allocation through devm_iio_device_alloc().

Accept only INDIO_DIRECT_MODE. Triggered modes require additional C-side state that this abstraction does not initialize. In particular, INDIO_EVENT_TRIGGERED exposes trigger selection that requires a valid pollfunc_event.

The initial abstraction intentionally supports read_raw only. It does not expose write_raw, buffers, triggers, events, extended attributes, or available-value attributes.

---
 include/linux/iio/iio.h         |   6 +-
 rust/bindings/bindings_helper.h |   2 +
 rust/kernel/iio.rs              | 480 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 4 files changed, 488 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/iio.rs
include/linux/iio/iio.h +4 -2
index 711c00f67371..512b1829f661 100644
@@ -445,8 +445,10 @@ struct iio_trigger; /* forward declaration */
  * @read_raw:		function to request a value from the device.
  *			mask specifies which value. Note 0 means a reading of
  *			the channel in question.  Return value will specify the
- *			type of value returned by the device. val and val2 will
- *			contain the elements making up the returned value.
+ *			type of value returned by the device. val and val2
+ *			point to writable integer storage valid for the
+ *			duration of the callback. The return value determines
+ *			which outputs contain meaningful data.
  * @read_raw_multi:	function to return values from the device.
  *			mask specifies which value. Note 0 means a reading of
  *			the channel in question.  Return value will specify the
rust/bindings/bindings_helper.h +2 -0
index 1124785e210b..f311959bab18 100644
@@ -62,6 +62,8 @@
 #include <linux/firmware.h>
 #include <linux/fs.h>
 #include <linux/i2c.h>
+#include <linux/iio/iio.h>
+#include <linux/iio/types.h>
 #include <linux/interrupt.h>
 #include <linux/io-pgtable.h>
 #include <linux/ioport.h>
rust/kernel/iio.rs new file +480 -0

480 lines not on this page · raw message

rust/kernel/lib.rs +2 -0
index 68f4d9a3425d..726a23e2d579 100644
@@ -81,6 +81,8 @@
 #[cfg(CONFIG_I2C = "y")]
 pub mod i2c;
 pub mod id_pool;
+#[cfg(CONFIG_IIO)]
+pub mod iio;
 #[doc(hidden)]
 pub mod impl_flags;
 pub mod init;
Signature · 1 line
2.50.0
#4 lore raw

RFC PATCH v6 4/4 iio: position: add Rust driver for ams AS5600

In reply to Muchamad Coirul Anwar

Add a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor.

Expose the raw angle and scale through the IIO sysfs interface in direct mode. Read the status register before each angle sample and return ENODATA when the magnet-detected bit is clear. Serialize the status and angle transaction sequence with a mutex and propagate I2C transport errors directly to userspace.

The AS5600 stores the raw angle with the high byte at register 0x0c. Use the byte-swapped SMBus word helper and mask the result to 12 bits.

---
 drivers/iio/position/Kconfig   |  11 ++
 drivers/iio/position/Makefile  |   1 +
 drivers/iio/position/as5600.rs | 177 +++++++++++++++++++++++++++++++++
 rust/kernel/bits.rs            |  29 ++++++
 4 files changed, 218 insertions(+)
 create mode 100644 drivers/iio/position/as5600.rs
drivers/iio/position/Kconfig +11 -0
index 1576a6380b53..14ed4bef82e1 100644
@@ -6,6 +6,17 @@
 
 menu "Linear and angular position sensors"
 
+config AS5600
+	tristate "ams AS5600 magnetic rotary position sensor"
+	depends on I2C=y && RUST
+	help
+	  Support for the ams OSRAM AS5600 12-bit magnetic rotary
+	  position sensor. Provides in_angl_raw (0-4095) and
+	  in_angl_scale (radians per LSB) via sysfs.
+
+	  To compile this driver as a module, choose M here: the
+	  module will be called as5600.
+
 config IQS624_POS
 	tristate "Azoteq IQS624/625 angular position sensors"
 	depends on MFD_IQS62X || COMPILE_TEST
drivers/iio/position/Makefile +1 -0
index d70902f2979d..2d26f6d6ace3 100644
@@ -4,5 +4,6 @@
 
 # When adding new entries keep the list in alphabetical order
 
+obj-$(CONFIG_AS5600) += as5600.o
 obj-$(CONFIG_HID_SENSOR_CUSTOM_INTEL_HINGE) += hid-sensor-custom-intel-hinge.o
 obj-$(CONFIG_IQS624_POS)	+= iqs624-pos.o
drivers/iio/position/as5600.rs new file +177 -0

177 lines not on this page · raw message

rust/kernel/bits.rs +29 -0
index 2daead125626..a6537a668dd6 100644
@@ -41,6 +41,7 @@ pub const fn [<bit_ $ty>](n: u32) -> $ty {
 impl_bit_fn!(u32);
 impl_bit_fn!(u16);
 impl_bit_fn!(u8);
+impl_bit_fn!(usize);
 
 macro_rules! impl_genmask_fn {
     (
@@ -203,3 +204,31 @@ pub const fn [<genmask_ $ty>](range: RangeInclusive<u32>) -> $ty {
     /// assert_eq!(genmask_u8(0..=7), u8::MAX);
     /// ```
 );
+
+impl_genmask_fn!(
+    usize,
+    /// # Examples
+    ///
+    /// ```
+    /// # #![expect(clippy::reversed_empty_ranges)]
+    /// # use kernel::bits::genmask_checked_usize;
+    /// assert_eq!(genmask_checked_usize(0..=0), Some(0b1));
+    /// assert_eq!(genmask_checked_usize(0..=3), Some(0b1111));
+    /// assert_eq!(genmask_checked_usize(1..=3), Some(0b1110));
+    ///
+    /// // `200` is out of the supported bit range on all platforms.
+    /// assert_eq!(genmask_checked_usize(0..=200), None);
+    ///
+    /// // Invalid range where the start is bigger than the end.
+    /// assert_eq!(genmask_checked_usize(5..=2), None);
+    /// ```
+    ,
+    /// # Examples
+    ///
+    /// ```
+    /// # use kernel::bits::genmask_usize;
+    /// assert_eq!(genmask_usize(0..=0), 0b1);
+    /// assert_eq!(genmask_usize(0..=3), 0b1111);
+    /// assert_eq!(genmask_usize(1..=3), 0b1110);
+    /// ```
+);
Signature · 1 line
2.50.0
maintainer
#5 lore raw
In reply to Muchamad Coirul Anwar

Hi Muchamad,

Reviewed the lifetime/teardown contracts you asked about. read_raw() has a problem: it takes parent: &Device<Bound> and recovers &I2cClient<Bound> via TryFrom. That conversion just got removed upstream ("rust: i2c:
remove TryFrom<&Device> implementation for &I2cClient", use-after-free, unrelated thread), so this won't compile anymore. More importantly, Gary Guo made the point that needing the conversion at all is the actual design issue: a class device shouldn't reach back into a generic parent reference during a callback -- whatever bus-specific resource it needs should be captured once, at registration time, and handed back via its own private data.

Concretely, this means dropping devres and letting Data<'bound> carry a borrowed reference directly, which it's designed for (Driver::Data<'bound>: Send + 'bound):

  pub struct As5600Priv<'a> {
      client: &'a I2cClient<Bound>,
      #[pin]
      io_lock: Mutex<()>,
  }

unsafe impl Send for As5600Priv<'_> {}
unsafe impl Sync for As5600Priv<'_> {}

  unsafe impl IioDriver for As5600Priv<'_> {
      fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo)
          -> Result<IioVal> {
          let client = self.client;
          ...
      }
  }

In probe(), capture the client once via deref coercion (Core -> Bound) and split the driver struct so the registered IIO device carries the same 'bound lifetime:

struct As5600;

  struct As5600Data<'bound> {
      _iio_dev: Device<As5600Priv<'bound>, Registered>,
  }

  impl Driver for As5600 {
      type Data<'bound> = As5600Data<'bound>;
      fn probe<'bound>(dev: &'bound I2cClient<Core<'_>>, ...) -> ... {
          let client: &'bound I2cClient<Bound> = dev;
          ...
      }
  }

register() then just returns Device<T, Registered> directly instead of transferring it to parent devres -- that transfer is what forced T:
'static in the first place, which is what made storing the borrowed client impossible and pushed you toward TryFrom.

I built this end to end against current rust-next: compiles clean, zero warnings, and zero changes to rust/kernel/i2c.rs. Happy to send the full diff if it's useful as a starting point for v7.

Cheers
Igor

#6 lore raw
Quoted 53 lines · Igor Korotin

Hi Muchamad,

Reviewed the lifetime/teardown contracts you asked about. read_raw() has a problem: it takes parent: &Device<Bound> and recovers &I2cClient<Bound> via TryFrom. That conversion just got removed upstream ("rust: i2c:
remove TryFrom<&Device> implementation for &I2cClient", use-after-free, unrelated thread), so this won't compile anymore. More importantly, Gary Guo made the point that needing the conversion at all is the actual design issue: a class device shouldn't reach back into a generic parent reference during a callback -- whatever bus-specific resource it needs should be captured once, at registration time, and handed back via its own private data.

Concretely, this means dropping devres and letting Data<'bound> carry a borrowed reference directly, which it's designed for (Driver::Data<'bound>: Send + 'bound):

  pub struct As5600Priv<'a> {
      client: &'a I2cClient<Bound>,
      #[pin]
      io_lock: Mutex<()>,
  }

unsafe impl Send for As5600Priv<'_> {}
unsafe impl Sync for As5600Priv<'_> {}

  unsafe impl IioDriver for As5600Priv<'_> {
      fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo)
          -> Result<IioVal> {
          let client = self.client;
          ...
      }
  }

In probe(), capture the client once via deref coercion (Core -> Bound) and split the driver struct so the registered IIO device carries the same 'bound lifetime:

struct As5600;

  struct As5600Data<'bound> {
      _iio_dev: Device<As5600Priv<'bound>, Registered>,
  }

  impl Driver for As5600 {
      type Data<'bound> = As5600Data<'bound>;
      fn probe<'bound>(dev: &'bound I2cClient<Core<'_>>, ...) -> ... {
          let client: &'bound I2cClient<Bound> = dev;
          ...
      }
  }
Quoted 8 lines

register() then just returns Device<T, Registered> directly instead of transferring it to parent devres -- that transfer is what forced T:
'static in the first place, which is what made storing the borrowed client impossible and pushed you toward TryFrom.

I built this end to end against current rust-next: compiles clean, zero warnings, and zero changes to rust/kernel/i2c.rs. Happy to send the full diff if it's useful as a starting point for v7.

Hi Igor,

Thanks for working through this and building the changes. I'd be glad to use your approach for v7, and I'd appreciate seeing the full diff you offered.

I got the lifetime model wrong in v5 by storing an ARef<I2cClient<Bound>>. I only realized that while fixing the documentation for v6. In v6 I stopped storing that ARef, but ended up relying on TryFrom in read_raw() instead.

Storing the client reference in the IIO private data rather than converting the parent back in read_raw() makes sense. I'll check the lifetime and teardown details as I prepare v7, and I'll acknowledge your contribution.

Thanks again,
Coirul

Quoted 2 lines

Cheers
Igor

maintainer
#7 lore raw

Hi Coirul,

Here's the full diff, applied on top of your v6 patches 3 and 4.

drivers/iio/position/as5600.rs +32 -19
index b72775241e81..f2897fbf8aa2 100644
@@ -36,7 +36,8 @@
         Device,
         IioChanInfo,
         IioDriver,
-        IioVal, //
+        IioVal,
+        Registered, //
     },
     io::Io,
     module_i2c_driver,
@@ -65,14 +66,12 @@
 
 i2c_device_table!(
     I2C_TABLE,
-    MODULE_I2C_TABLE,
     <As5600 as Driver>::IdInfo,
     [(DeviceId::new(c"as5600"), ())]
 );
 
 of_device_table!(
     OF_TABLE,
-    MODULE_OF_TABLE,
     <As5600 as Driver>::IdInfo,
     [(of::DeviceId::new(c"ams,as5600"), ())]
 );
@@ -97,25 +96,29 @@ unsafe impl Sync for As5600Channels {}
 });
 
 #[pin_data]
-struct As5600Priv {
+struct As5600Priv<'a> {
+    client: &'a I2cClient<Bound>,
     #[pin]
     io_lock: Mutex<()>,
 }
 
+// SAFETY: `I2cClient<Bound>` methods go through kernel I2C core functions
+// that provide their own synchronization (bus locking); no `&self` method
+// exposes interior mutability. The borrowed `client` field can therefore be
+// safely accessed and shared across threads like the rest of `As5600Priv`.
+unsafe impl Send for As5600Priv<'_> {}
+// SAFETY: See above.
+unsafe impl Sync for As5600Priv<'_> {}
+
 // SAFETY: AS5600_CHANNELS contains one valid, immutable IIO_ANGL channel
 // exposing only RAW and SCALE. It has no event or extension callbacks,
 // and all optional pointer fields are null.
-unsafe impl IioDriver for As5600Priv {
-    fn read_raw(
-        &self,
-        parent: &kernel::device::Device<Bound>,
-        _chan: *const iio_chan_spec,
-        info: IioChanInfo,
-    ) -> Result<IioVal> {
+unsafe impl IioDriver for As5600Priv<'_> {
+    fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo) -> Result<IioVal> {
         match info {
             IioChanInfo::Raw => {
                 let _guard = self.io_lock.lock();
-                let client: &I2cClient<Bound> = parent.try_into()?;
+                let client = self.client;
 
                 let io = client.smbus_io();
                 // Read status register to verify magnet presence before
@@ -142,14 +145,17 @@ fn channels(&self) -> &'static [iio_chan_spec] {
     }
 }
 
+struct As5600;
+
 #[pin_data]
-struct As5600 {
-    _registration: (),
+struct As5600Data<'bound> {
+    #[pin]
+    _iio_dev: Device<As5600Priv<'bound>, Registered>,
 }
 
 impl Driver for As5600 {
     type IdInfo = ();
-    type Data<'bound> = As5600;
+    type Data<'bound> = As5600Data<'bound>;
 
     const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
@@ -162,15 +168,22 @@ fn probe<'bound>(
         dev: &'bound I2cClient<Core<'_>>,
         _id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
-        try_pin_init!(As5600 {
-            _registration: {
+        try_pin_init!(As5600Data {
+            _iio_dev: {
+                // Deref coercion: I2cClient<Core<'_>> -> I2cClient<Bound>.
+                let client: &'bound I2cClient<Bound> = dev;
+
                 let priv_init = pin_init!(As5600Priv {
+                    client,
                     io_lock <- new_mutex!(()),
                 });
 
-                Device::build_device(dev.as_ref(), c"as5600", INDIO_DIRECT_MODE, priv_init)?
-                    .register(&crate::THIS_MODULE)?;
+                let unregistered =
+                    Device::build_device(dev.as_ref(), c"as5600", INDIO_DIRECT_MODE, priv_init)?;
+                let registered =
+                    unregistered.register(kernel::module::this_module::<crate::LocalModule>())?;
                 dev_dbg!(dev.as_ref(), "AS5600 magnetic position sensor ready\n");
+                registered
             }
         })
     }
rust/kernel/iio.rs +21 -36

123 lines not on this page · raw message

Cheers
Igor

#8 lore raw
Quoted 250 lines · Igor Korotin

Hi Coirul,

Here's the full diff, applied on top of your v6 patches 3 and 4.

drivers/iio/position/as5600.rs +32 -19
index b72775241e81..f2897fbf8aa2 100644
@@ -36,7 +36,8 @@
         Device,
         IioChanInfo,
         IioDriver,
-        IioVal, //
+        IioVal,
+        Registered, //
     },
     io::Io,
     module_i2c_driver,
@@ -65,14 +66,12 @@
 
 i2c_device_table!(
     I2C_TABLE,
-    MODULE_I2C_TABLE,
     <As5600 as Driver>::IdInfo,
     [(DeviceId::new(c"as5600"), ())]
 );
 
 of_device_table!(
     OF_TABLE,
-    MODULE_OF_TABLE,
     <As5600 as Driver>::IdInfo,
     [(of::DeviceId::new(c"ams,as5600"), ())]
 );
@@ -97,25 +96,29 @@ unsafe impl Sync for As5600Channels {}
 });
 
 #[pin_data]
-struct As5600Priv {
+struct As5600Priv<'a> {
+    client: &'a I2cClient<Bound>,
     #[pin]
     io_lock: Mutex<()>,
 }
 
+// SAFETY: `I2cClient<Bound>` methods go through kernel I2C core functions
+// that provide their own synchronization (bus locking); no `&self` method
+// exposes interior mutability. The borrowed `client` field can therefore be
+// safely accessed and shared across threads like the rest of `As5600Priv`.
+unsafe impl Send for As5600Priv<'_> {}
+// SAFETY: See above.
+unsafe impl Sync for As5600Priv<'_> {}
+
 // SAFETY: AS5600_CHANNELS contains one valid, immutable IIO_ANGL channel
 // exposing only RAW and SCALE. It has no event or extension callbacks,
 // and all optional pointer fields are null.
-unsafe impl IioDriver for As5600Priv {
-    fn read_raw(
-        &self,
-        parent: &kernel::device::Device<Bound>,
-        _chan: *const iio_chan_spec,
-        info: IioChanInfo,
-    ) -> Result<IioVal> {
+unsafe impl IioDriver for As5600Priv<'_> {
+    fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo) -> Result<IioVal> {
         match info {
             IioChanInfo::Raw => {
                 let _guard = self.io_lock.lock();
-                let client: &I2cClient<Bound> = parent.try_into()?;
+                let client = self.client;
 
                 let io = client.smbus_io();
                 // Read status register to verify magnet presence before
@@ -142,14 +145,17 @@ fn channels(&self) -> &'static [iio_chan_spec] {
     }
 }
 
+struct As5600;
+
 #[pin_data]
-struct As5600 {
-    _registration: (),
+struct As5600Data<'bound> {
+    #[pin]
+    _iio_dev: Device<As5600Priv<'bound>, Registered>,
 }
 
 impl Driver for As5600 {
     type IdInfo = ();
-    type Data<'bound> = As5600;
+    type Data<'bound> = As5600Data<'bound>;
 
     const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
@@ -162,15 +168,22 @@ fn probe<'bound>(
         dev: &'bound I2cClient<Core<'_>>,
         _id_info: Option<&'bound Self::IdInfo>,
     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
-        try_pin_init!(As5600 {
-            _registration: {
+        try_pin_init!(As5600Data {
+            _iio_dev: {
+                // Deref coercion: I2cClient<Core<'_>> -> I2cClient<Bound>.
+                let client: &'bound I2cClient<Bound> = dev;
+
                 let priv_init = pin_init!(As5600Priv {
+                    client,
                     io_lock <- new_mutex!(()),
                 });
 
-                Device::build_device(dev.as_ref(), c"as5600", INDIO_DIRECT_MODE, priv_init)?
-                    .register(&crate::THIS_MODULE)?;
+                let unregistered =
+                    Device::build_device(dev.as_ref(), c"as5600", INDIO_DIRECT_MODE, priv_init)?;
+                let registered =
+                    unregistered.register(kernel::module::this_module::<crate::LocalModule>())?;
                 dev_dbg!(dev.as_ref(), "AS5600 magnetic position sensor ready\n");
+                registered
             }
         })
     }
rust/kernel/iio.rs +20 -35
index 9ad2f50948de..4648424c7600 100644
@@ -21,7 +21,6 @@
         self,
         Bound, //
     },
-    devres,
     error::{
         code::*,
         to_result,
@@ -159,15 +158,12 @@ pub enum IioVal {
 pub unsafe trait IioDriver: Send + Sync {
     /// Called by the IIO core to read channel information.
     ///
-    /// `parent` is the parent device supplied to [`Device::build_device`].
     /// `chan` identifies the channel, and `info` selects the requested
-    /// information, such as its raw value or scale.
-    fn read_raw(
-        &self,
-        parent: &device::Device<Bound>,
-        chan: *const iio_chan_spec,
-        info: IioChanInfo,
-    ) -> Result<IioVal>;
+    /// information, such as its raw value or scale. Implementors must
+    /// capture whatever bus-specific resources they need at registration
+    /// time (see [`Device::build_device`]) rather than re-deriving them
+    /// from a generic parent reference here.
+    fn read_raw(&self, chan: *const iio_chan_spec, info: IioChanInfo) -> Result<IioVal>;
 
     /// Returns the channel specifications for this driver.
     ///
@@ -204,16 +200,6 @@ fn channels(&self) -> &'static [iio_chan_spec] {
     // initialized `T` that remains valid for the duration of this callback.
     let driver = unsafe { &*priv_ptr };
 
-    // SAFETY: `indio_dev` is valid by the callback contract. Its parent
-    // was supplied as a bound device to `build_device`.
-    //
-    // During registration, the builder holds that bound parent borrow.
-    // After ownership is transferred, parent devres runs the registered
-    // device's destructor, which unregisters the IIO device and drains
-    // the supported read_raw paths before destroying the private data.
-    // The parent therefore remains bound throughout this callback.
-    let parent = unsafe { device::Device::<Bound>::from_raw((*indio_dev).dev.parent) };
-
     // `info` is `long` from C. Negative values and values > u32::MAX
     // are unsupported iio_chan_info variants; both map to EINVAL.
     let info_enum = match u32::try_from(info)
@@ -224,7 +210,7 @@ fn channels(&self) -> &'static [iio_chan_spec] {
         None => return EINVAL.to_errno(),
     };
 
-    match driver.read_raw(parent, chan, info_enum) {
+    match driver.read_raw(chan, info_enum) {
         Ok(IioVal::Int(v)) => {
             // SAFETY: `val` is valid per the function's Safety contract above.
             // `val2` is not written; `IIO_VAL_INT` signals to the IIO core
@@ -271,11 +257,8 @@ fn channels(&self) -> &'static [iio_chan_spec] {
 pub struct Registered;
 
 /// An initialized IIO device awaiting registration.
-///
-/// The parent remains bound until this builder is consumed or dropped.
-pub struct UnregisteredDevice<'a, T: IioDriver> {
+pub struct UnregisteredDevice<T: IioDriver> {
     device: Device<T>,
-    parent: &'a device::Device<Bound>,
 }
 
 /// An owned IIO device with in-place initialized driver data.
@@ -363,12 +346,12 @@ impl<T: IioDriver> Device<T> {
     /// Allocation and initialization errors are propagated.
     ///
     /// Call [`UnregisteredDevice::register`] to register the device.
-    pub fn build_device<'a, E>(
-        parent: &'a device::Device<Bound>,
+    pub fn build_device<E>(
+        parent: &device::Device<Bound>,
         name: &'static CStr,
         modes: u32,
         init: impl PinInit<T, E>,
-    ) -> Result<UnregisteredDevice<'a, T>>
+    ) -> Result<UnregisteredDevice<T>>
     where
         Error: From<E>,
     {
@@ -406,7 +389,7 @@ pub fn build_device<'a, E>(
         // large enough for `T`. The private data remains at a fixed address in
         // the separate IIO allocation until it is dropped. On initialization
         // failure, the error path only frees the allocation.
-        let init_result = unsafe { init.__pinned_init(priv_ptr) };
+        let init_result = unsafe { pin_init::raw_try_init(priv_ptr, init) };
         if let Err(e) = init_result {
             // SAFETY: `pin_init` guarantees partial-init rollback internally.
             // `priv_` memory was not fully initialized, so we only free the
@@ -446,21 +429,23 @@ pub fn build_device<'a, E>(
             (*indio_dev).modes = modes;
         }
 
-        Ok(UnregisteredDevice { device, parent })
+        Ok(UnregisteredDevice { device })
     }
 }
 
-impl<T: IioDriver + 'static> UnregisteredDevice<'_, T> {
-    /// Registers the IIO device and transfers ownership to parent devres.
+impl<T: IioDriver> UnregisteredDevice<T> {
+    /// Registers the IIO device.
     ///
-    /// Parent resource teardown unregisters the device and completes its
-    /// supported `read_raw` callbacks before destroying the private data.
+    /// The caller owns the returned, pinned [`Device<T, Registered>`] and is
+    /// responsible for keeping it alive for as long as the registration
+    /// should remain visible to userspace; dropping it unregisters the
+    /// device and tears down the private data.
     ///
     /// On failure, the device is released and any successful registration is
     /// undone.
     #[inline]
-    pub fn register(self, module: &'static ThisModule) -> Result {
-        let Self { device, parent } = self;
+    pub fn register(self, module: &'static ThisModule) -> Result<Device<T, Registered>> {
+        let Self { device } = self;
 
         // SAFETY: `device.indio_dev` is a valid, fully-initialized `iio_dev`
         // allocated by `iio_device_alloc` with its name, info vtable, channels,

rust/kernel/iio.rs pub fn register(self, module: &'static ThisModule) -> Result { · line 465

Quoted 7 lines
rust/kernel/iio.rs +1 -1
@@ -475,6 +460,6 @@ pub fn register(self, module: &'static ThisModule) -> Result {
         };
         forget(device);
 
-        devres::register(parent, registered, GFP_KERNEL)
+        Ok(registered)
     }
 }

Hi Igor,

Thank you for your help. I really appreciate it. I've applied your changes locally, and the build succeeds.

I hadn't realized that pin-init had changed upstream and that your patch also adapted the AS5600 and IIO code to those changes. My version appears to have fallen quite far behind upstream. Catching up on my own might have taken me weeks, perhaps even longer if I had run into other issues along the way.

This also seems to address the earlier discussion around the IIO design and the TryFrom implementation. I plan to test it on my hardware this weekend.

Thank you so much,
Coirul

Quoted 2 lines

Cheers
Igor

#9 lore raw

Hi Igor,

I've tested your changes on an AS5600 connected to a BeagleBone Black over I2C2. Everything works. I'll put the details in the v7 cover letter.

One thing I forgot to ask before, the registration rework in the IIO abstraction and the driver is your code. Are you fine with me adding

to patches 3 and 4 in v7? I don't want to add your Signed-off-by without asking.

I will send v7 shortly.

Thanks,
Coirul

maintainer
#10 lore raw

Hi Coirul,

Sorry for the slow reply. Co-developed-by/Signed-off-by is fine with me -- your call either way, I don't mind.

Cheers
Igor

#11 lore raw
In reply to Muchamad Coirul Anwar

Hi Coirul,

Thanks for the series. I read through v6, including Igor's registration rework proposal in this thread. The comments below do not overlap with that rework and should carry over to v7 unchanged, as far as I can tell.

1. clippy warnings

make LLVM=1 CLIPPY=1 reports four warnings on this series, which the Rust CI gates on. Three are clippy::ptr_as_ptr in the IIO abstraction and one is clippy::useless_conversion in the driver:

--- a/rust/kernel/iio.rs
+++ b/rust/kernel/iio.rs
@@ -202,1 +202,1 @@
- let priv_ptr = unsafe { (*indio_dev).priv_ as *mut T };
+ let priv_ptr = unsafe { (*indio_dev).priv_.cast::<T>() };

(the same pattern at lines 334 and 397; line 334 is already inside an unsafe block and just needs .cast::<T>())

--- a/drivers/iio/position/as5600.rs
+++ b/drivers/iio/position/as5600.rs
@@ -133,1 +133,1 @@
- Ok(IioVal::Int(angle as i32))
+ Ok(IioVal::Int(i32::from(angle)))

2. ignored doctest in the SMBus word helper

The example on smbus_read_word_swapped() (rust/kernel/i2c.rs:841) is marked "ignore" and references driver-specific facts (the AS5600). Ignored examples are not compiled or run by rusttest, so the helper currently ships with no tested usage. A generic, compilable example works here:

    --- a/rust/kernel/i2c.rs
    +++ b/rust/kernel/i2c.rs
    @@ -841,8 +841,15 @@
     /// ```
    -/// // AS5600 stores the 12-bit raw angle at command byte 0x0C with its
    -/// // high byte first, so the SMBus (low byte first) word result must
    -/// // be swapped.
    -/// let raw = client.smbus_read_word_swapped(0x0C)?;
    -/// # Ok::<(), Error>(())
    +/// use kernel::{i2c::I2cClient, prelude::*};
    +///
    +/// fn read_hi_first_register(client: &I2cClient<kernel::device::Bound>) -> Result<u16> {
    +///     // A device whose 16-bit register selected by command byte 0x0C
    +///     // transmits the high byte first needs the SMBus (low byte first)
    +///     // word swapped.
    +///     client.smbus_read_word_swapped(0x0C)
    +/// }
     /// ```

3. repeated unsafe blocks in the SMBus access helpers

Patch 2 implements the FallibleIoCapable impls for u8/u16 with five near-identical unsafe blocks wrapping bindings::i2c_smbus_* calls plus error conversion. Extracting four small safe helpers would put the safety argument in one place and turn each call site into a one-liner:

fn smbus_read_byte(client: &I2cClient<device::Bound>, reg: u8)
-> Result<u8>;
fn smbus_write_byte(client: &I2cClient<device::Bound>, reg: u8, value: u8)
-> Result;
fn smbus_read_word_data(client: &I2cClient<device::Bound>, reg: u8)
-> Result<u16>;
fn smbus_write_word_data(client: &I2cClient<device::Bound>, reg: u8, value: u16)
-> Result;

For example, io_try_write for u8 then reduces to smbus_write_byte(client, reg, value). Happy to send the full diff if that is useful as a starting point.

With 1 and 2 applied (and 3 sketched on top), make LLVM=1 CLIPPY=1 drivers/iio/position/as5600.o builds with no warnings and the rusttest doctests pass.

Thanks,
Shuai Liu

#12 lore raw
Quoted 12 lines · Shuai Liu

1. clippy warnings

make LLVM=1 CLIPPY=1 reports four warnings on this series, which the Rust CI gates on. Three are clippy::ptr_as_ptr in the IIO abstraction and one is clippy::useless_conversion in the driver:

--- a/rust/kernel/iio.rs
+++ b/rust/kernel/iio.rs
@@ -202,1 +202,1 @@
- let priv_ptr = unsafe { (*indio_dev).priv_ as *mut T };
+ let priv_ptr = unsafe { (*indio_dev).priv_.cast::<T>() };

Quoted 8 lines

(the same pattern at lines 334 and 397; line 334 is already inside an unsafe block and just needs .cast::<T>())

--- a/drivers/iio/position/as5600.rs
+++ b/drivers/iio/position/as5600.rs
@@ -133,1 +133,1 @@
- Ok(IioVal::Int(angle as i32))
+ Ok(IioVal::Int(i32::from(angle)))

Hi Shuai

Thanks for catching the Clippy warnings. I reproduced and fixed them, and the Clippy build now completes without warnings. I also replaced the ignored, AS5600-specific example with a generic no_run example, which is now compile-checked without being run.

Quoted 44 lines

2. ignored doctest in the SMBus word helper

The example on smbus_read_word_swapped() (rust/kernel/i2c.rs:841) is marked "ignore" and references driver-specific facts (the AS5600). Ignored examples are not compiled or run by rusttest, so the helper currently ships with no tested usage. A generic, compilable example works here:

    --- a/rust/kernel/i2c.rs
    +++ b/rust/kernel/i2c.rs
    @@ -841,8 +841,15 @@
     /// ```
    -/// // AS5600 stores the 12-bit raw angle at command byte 0x0C with its
    -/// // high byte first, so the SMBus (low byte first) word result must
    -/// // be swapped.
    -/// let raw = client.smbus_read_word_swapped(0x0C)?;
    -/// # Ok::<(), Error>(())
    +/// use kernel::{i2c::I2cClient, prelude::*};
    +///
    +/// fn read_hi_first_register(client: &I2cClient<kernel::device::Bound>) -> Result<u16> {
    +///     // A device whose 16-bit register selected by command byte 0x0C
    +///     // transmits the high byte first needs the SMBus (low byte first)
    +///     // word swapped.
    +///     client.smbus_read_word_swapped(0x0C)
    +/// }
     /// ```

3. repeated unsafe blocks in the SMBus access helpers

Patch 2 implements the FallibleIoCapable impls for u8/u16 with five near-identical unsafe blocks wrapping bindings::i2c_smbus_* calls plus error conversion. Extracting four small safe helpers would put the safety argument in one place and turn each call site into a one-liner:

fn smbus_read_byte(client: &I2cClient<device::Bound>, reg: u8)
-> Result<u8>;
fn smbus_write_byte(client: &I2cClient<device::Bound>, reg: u8, value: u8)
-> Result;
fn smbus_read_word_data(client: &I2cClient<device::Bound>, reg: u8)
-> Result<u16>;
fn smbus_write_word_data(client: &I2cClient<device::Bound>, reg: u8, value: u16)
-> Result;

Quoted 7 lines

For example, io_try_write for u8 then reduces to smbus_write_byte(client, reg, value). Happy to send the full diff if that is useful as a starting point.

With 1 and 2 applied (and 3 sketched on top), make LLVM=1 CLIPPY=1 drivers/iio/position/as5600.o builds with no warnings and the rusttest doctests pass.

I also followed your I2C refactoring suggestion and added the four safe helpers as methods on I2cClient<device::Bound>.

Thanks for taking the time to review this. I'll Cc you when I send v7.

Thanks,
Coirul

Quoted 3 lines

Thanks,
Shuai Liu