Skip to contentSkip to conversation

iio: position: add Rust driver for ams AS5600

RFC PATCH In review Muchamad Coirul Anwar 7 participants 21 messages Dec 1 – Dec 5

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

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

This series adds a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. It also adds fallible I/O, SMBus access, and the IIO abstractions needed by the driver. The driver exposes raw angle and scale through IIO sysfs.

The internal I2C register interface remains an interim approach while Rust regmap abstractions are unavailable. Following the RFC v7 discussion [1], the long-term plan is to migrate drivers like this to regmap to avoid duplication, using this internal interface only until Rust regmap support lands. Feedback from I2C and Rust maintainers on this approach is still welcome.

Thanks to Igor Korotin for co-developing the device ownership and bound-client lifetime rework in Patches 3 and 4, and for reporting the two Clippy warnings in Patch 3/4 of v7. Thanks also to Markus Probst for suggesting Sync on I2cClient<device::Bound> for Patch 2/4.

Igor reviewed Patch 2/4 in v7, but since I added Sync on I2cClient<device::Bound> and updated some docs afterward, I did not carry his Reviewed-by: tag forward. Another review would be appreciated.

[1] https://lore.kernel.org/all/20261128235858.39e8e5f6@jic23-hlaptop/

---

Previous versions:

v7: https://lore.kernel.org/all/[email protected]/
v6: https://lore.kernel.org/all/[email protected]/

Changes since RFC v7:

- Rebase on top of Linux v7.4-rc4 (which includes the removal of TryFrom<&Device> for &I2cClient).
- Patch 2/4: Implement Sync for I2cClient<device::Bound>, as suggested by Markus Probst, removing the need for
unsafe impl Send/Sync on As5600Priv. Update SMBus documentation and invariant comments.
- Patch 3/4: Gate pub mod iio; on #[cfg(CONFIG_IIO = "y")].
- Patch 3/4: Fix the two Clippy warnings in rust/kernel/iio.rs reported by Igor Korotin.
- Patch 3/4: Thread the 'parent bound lifetime through Device and UnregisteredDevice, and mark UnregisteredDevice::register() as unsafe.
- Patch 4/4: Remove unsafe impl Send/Sync from As5600Priv and bind Device to the 'bound parent lifetime.

Testing:

Clippy (CLIPPY=1) and debug builds (CONFIG_RUST_DEBUG_ASSERTIONS, CONFIG_KFENCE, CONFIG_UBSAN, CONFIG_PROVE_LOCKING, and CONFIG_DEBUG_KMEMLEAK) passed on ARMv7 (I2C=y, IIO=y, AS5600=m), with no warnings on rust/kernel.o or drivers/iio/position/as5600.o.

Runtime testing was performed on a BeagleBone Black with an AS5600 on i2c-2 at 0x36:
- Raw angle (including magnet rotation) and scale reads via sysfs, and ENODATA when the magnet-detected bit is clear.
- I2C bus disconnect returning -EREMOTEIO and recovering on reconnect, plus clean module removal while in bus error state.
- 10 concurrent readers, 50 unbind/rebind cycles (including concurrent reads), 50 module load/unload cycles, and module removal during active reads and with an open sysfs file descriptor.
- KFENCE, UBSAN, lockdep, and kmemleak reported no issues (KASAN was disabled because 32-bit ARM selects HAVE_RUST only when !KASAN).

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  | 193 ++++++++++++
 include/linux/iio/iio.h         |   6 +-
 rust/bindings/bindings_helper.h |   2 +
 rust/kernel/bits.rs             |  29 ++
 rust/kernel/i2c.rs              | 243 ++++++++++++++-
 rust/kernel/iio.rs              | 519 ++++++++++++++++++++++++++++++++
 rust/kernel/io.rs               |  62 ++--
 rust/kernel/lib.rs              |   2 +
 10 files changed, 1048 insertions(+), 20 deletions(-)
 create mode 100644 drivers/iio/position/as5600.rs
 create mode 100644 rust/kernel/iio.rs

base-commit: b6a9fa34ce4187cb69d3c588a4bbffc31ce5db8f

Signature · 1 line
2.50.0
#1 lore raw

RFC PATCH v8 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 | 62 ++++++++++++++++++++++++++++++++++-------------
 1 file changed, 45 insertions(+), 17 deletions(-)
rust/kernel/io.rs +45 -17
index a877df11a03e..b93a540c28da 100644
@@ -356,6 +356,31 @@ pub trait IoCapable<T>: IoBackend {
     fn io_write<'a>(view: Self::View<'a, T>, value: T);
 }
 
+/// I/O backend capability for operations that may fail independently of address validation.
+///
+/// Infallible backends implementing [`IoCapable`] also support fallible operations. Backends
+/// implementing only this trait cannot use the infallible [`Io`] accessors.
+pub trait FallibleIoCapable<T>: IoBackend {
+    /// Read from `view`, returning a transport error if the operation fails.
+    fn io_try_read<'a>(view: Self::View<'a, T>) -> Result<T>;
+
+    /// Write `value` to `view`, returning a transport error if the 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`.
@@ -759,7 +784,7 @@ fn copy_to_slice(self, data: &mut [u8])
     fn try_read8(self, offset: usize) -> Result<u8>
     where
         usize: IoLoc<Self::Target, u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_read(offset)
     }
@@ -769,7 +794,7 @@ fn try_read8(self, offset: usize) -> Result<u8>
     fn try_read16(self, offset: usize) -> Result<u16>
     where
         usize: IoLoc<Self::Target, u16>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_read(offset)
     }
@@ -779,7 +804,7 @@ fn try_read16(self, offset: usize) -> Result<u16>
     fn try_read32(self, offset: usize) -> Result<u32>
     where
         usize: IoLoc<Self::Target, u32>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_read(offset)
     }
@@ -789,7 +814,7 @@ fn try_read32(self, offset: usize) -> Result<u32>
     fn try_read64(self, offset: usize) -> Result<u64>
     where
         usize: IoLoc<Self::Target, u64>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_read(offset)
     }
@@ -799,7 +824,7 @@ fn try_read64(self, offset: usize) -> Result<u64>
     fn try_write8(self, value: u8, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_write(offset, value)
     }
@@ -809,7 +834,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>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_write(offset, value)
     }
@@ -819,7 +844,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>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_write(offset, value)
     }
@@ -829,7 +854,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>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_write(offset, value)
     }
@@ -958,9 +983,12 @@ fn try_read<T, L>(self, location: L) -> Result<T>
     where
         T: AsReprMut,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
-        Ok(io_read!(self, try: location))
+        let view = io_project!(self, try: location);
+        Ok(T::from_repr(Self::Backend::io_try_read(io_view_as_repr(
+            view,
+        ))?))
     }
 
     /// Generic fallible write with runtime bounds check.
@@ -991,10 +1019,10 @@ fn try_write<T, L>(self, location: L, value: T) -> Result
     where
         T: AsRepr,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
-        io_write!(self, try: location, value);
-        Ok(())
+        let view = io_project!(self, try: location);
+        Self::Backend::io_try_write(io_view_as_repr(view), T::into_repr(value))
     }
 
     /// Generic fallible write of a fully-located register value.
@@ -1037,7 +1065,7 @@ fn try_write_reg<T, L, V>(self, value: V) -> Result
         T: AsRepr,
         L: IoLoc<Self::Target, T>,
         V: LocatedRegister<Self::Target, Location = L, Value = T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
         let (location, value) = value.into_io_op();
 
@@ -1071,12 +1099,12 @@ fn try_update<T, L, F>(self, location: L, f: F) -> Result
     where
         T: AsReprMut,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
         F: FnOnce(T) -> T,
     {
         let view = io_project!(self, try: location);
-        view.write_val(f(view.read_val()));
-        Ok(())
+        let value = T::from_repr(Self::Backend::io_try_read(io_view_as_repr(view))?);
+        Self::Backend::io_try_write(io_view_as_repr(view), T::into_repr(f(value)))
     }
 
     /// Generic infallible read with compile-time bounds check.
Signature · 1 line
2.50.0
Tested-by on v8 1/4
#2 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 169 lines · Muchamad Coirul Anwar

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 | 62 ++++++++++++++++++++++++++++++++++-------------
 1 file changed, 45 insertions(+), 17 deletions(-)
rust/kernel/io.rs +43 -15
index a877df11a03e..b93a540c28da 100644
@@ -356,6 +356,31 @@ pub trait IoCapable<T>: IoBackend {
     fn io_write<'a>(view: Self::View<'a, T>, value: T);
 }
 
+/// I/O backend capability for operations that may fail independently of address validation.
+///
+/// Infallible backends implementing [`IoCapable`] also support fallible operations. Backends
+/// implementing only this trait cannot use the infallible [`Io`] accessors.
+pub trait FallibleIoCapable<T>: IoBackend {
+    /// Read from `view`, returning a transport error if the operation fails.
+    fn io_try_read<'a>(view: Self::View<'a, T>) -> Result<T>;
+
+    /// Write `value` to `view`, returning a transport error if the 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`.
@@ -759,7 +784,7 @@ fn copy_to_slice(self, data: &mut [u8])
     fn try_read8(self, offset: usize) -> Result<u8>
     where
         usize: IoLoc<Self::Target, u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_read(offset)
     }
@@ -769,7 +794,7 @@ fn try_read8(self, offset: usize) -> Result<u8>
     fn try_read16(self, offset: usize) -> Result<u16>
     where
         usize: IoLoc<Self::Target, u16>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_read(offset)
     }
@@ -779,7 +804,7 @@ fn try_read16(self, offset: usize) -> Result<u16>
     fn try_read32(self, offset: usize) -> Result<u32>
     where
         usize: IoLoc<Self::Target, u32>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_read(offset)
     }
@@ -789,7 +814,7 @@ fn try_read32(self, offset: usize) -> Result<u32>
     fn try_read64(self, offset: usize) -> Result<u64>
     where
         usize: IoLoc<Self::Target, u64>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_read(offset)
     }
@@ -799,7 +824,7 @@ fn try_read64(self, offset: usize) -> Result<u64>
     fn try_write8(self, value: u8, offset: usize) -> Result
     where
         usize: IoLoc<Self::Target, u8>,
-        Self::Backend: IoCapable<u8>,
+        Self::Backend: FallibleIoCapable<u8>,
     {
         self.try_write(offset, value)
     }
@@ -809,7 +834,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>,
-        Self::Backend: IoCapable<u16>,
+        Self::Backend: FallibleIoCapable<u16>,
     {
         self.try_write(offset, value)
     }
@@ -819,7 +844,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>,
-        Self::Backend: IoCapable<u32>,
+        Self::Backend: FallibleIoCapable<u32>,
     {
         self.try_write(offset, value)
     }
@@ -829,7 +854,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>,
-        Self::Backend: IoCapable<u64>,
+        Self::Backend: FallibleIoCapable<u64>,
     {
         self.try_write(offset, value)
     }
@@ -958,9 +983,12 @@ fn try_read<T, L>(self, location: L) -> Result<T>
     where
         T: AsReprMut,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
-        Ok(io_read!(self, try: location))
+        let view = io_project!(self, try: location);
+        Ok(T::from_repr(Self::Backend::io_try_read(io_view_as_repr(
+            view,
+        ))?))
     }
 
     /// Generic fallible write with runtime bounds check.
@@ -991,10 +1019,10 @@ fn try_write<T, L>(self, location: L, value: T) -> Result
     where
         T: AsRepr,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
-        io_write!(self, try: location, value);
-        Ok(())
+        let view = io_project!(self, try: location);
+        Self::Backend::io_try_write(io_view_as_repr(view), T::into_repr(value))
     }
 
     /// Generic fallible write of a fully-located register value.
@@ -1037,7 +1065,7 @@ fn try_write_reg<T, L, V>(self, value: V) -> Result
         T: AsRepr,
         L: IoLoc<Self::Target, T>,
         V: LocatedRegister<Self::Target, Location = L, Value = T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,
     {
         let (location, value) = value.into_io_op();
 
@@ -1071,12 +1099,12 @@ fn try_update<T, L, F>(self, location: L, f: F) -> Result
     where
         T: AsReprMut,
         L: IoLoc<Self::Target, T>,
-        Self::Backend: IoCapable<<T as AsRepr>::Repr>,
+        Self::Backend: FallibleIoCapable<<T as AsRepr>::Repr>,

rust/kernel/io.rs fn try_update<T, L, F>(self, location: L, f: F) -> Result · line 1110

Quoted 10 lines
rust/kernel/io.rs +2 -2
         F: FnOnce(T) -> T,
     {
         let view = io_project!(self, try: location);
-        view.write_val(f(view.read_val()));
-        Ok(())
+        let value = T::from_repr(Self::Backend::io_try_read(io_view_as_repr(view))?);
+        Self::Backend::io_try_write(io_view_as_repr(view), T::into_repr(f(value)))
     }
 
     /// Generic infallible read with compile-time bounds check.

Thanks
- Markus Probst

#3 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

In reply to Muchamad Coirul Anwar
Quoted 11 lines · Muchamad Coirul Anwar

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.

Drop unreferred Link tag(s), if it's for Suggested-by, no need, it's implied that it was Suggested. Moreover, since the mentioned person is in Cc list they have to give a tag to confirm that.

Quoted 1 line
Signature · 2 lines
With Best Regards,
Andy Shevchenko
#4 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 4 lines · Andy Shevchenko

Drop unreferred Link tag(s), if it's for Suggested-by, no need, it's implied that it was Suggested. Moreover, since the mentioned person is in Cc list they have to give a tag to confirm that.

I guess it is for the Suggested-by, which means the tags should be swapped, but having the Link for the Suggested-by is fine and we routinely do that. It is good to know where the suggestion came from and to understand if it matches what was actually suggested. And, in this one in particular, Danilo wrote some nice context and code there.

Also, Suggested-by is allowed to be added without the person giving it explicitly (but, of course, one needs to be careful to get it right).

Cheers,
Miguel

#5 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 7 lines · Miguel Ojeda
Quoted 4 lines · Andy Shevchenko

Drop unreferred Link tag(s), if it's for Suggested-by, no need, it's implied that it was Suggested. Moreover, since the mentioned person is in Cc list they have to give a tag to confirm that.

Quoted 5 lines

I guess it is for the Suggested-by, which means the tags should be swapped, but having the Link for the Suggested-by is fine and we routinely do that. It is good to know where the suggestion came from and to understand if it matches what was actually suggested. And, in this one in particular, Danilo wrote some nice context and code there.

Nice, but if this is the case, we need a reference in the commit message text like Link: $URL [1] and in the text "Danilo provided a context [1] bla-bla-bla".

IIRC Linus T. is grumpy about unreferred links (links that are need to be clicked and time potentially wasted to understand why the commit message contains them).

Quoted 2 lines

Also, Suggested-by is allowed to be added without the person giving it explicitly (but, of course, one needs to be careful to get it right).

Yes, it can, but there is an assumption that any Suggested-by has to be accompanied with Acked-by (or Reviewed-by) the person who suggested something.

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

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 4 lines · Andy Shevchenko

IIRC Linus T. is grumpy about unreferred links (links that are need to be clicked and time potentially wasted to understand why the commit message contains them).

I didn't understand Linus' emails back then to say we shouldn't have unreferred links at all anymore and thus to have to put extra sentences in the commit. From what I recall, it was about having Links that do not add information (in particular about the msgid ones because they could be located in other ways), and the one here in the patch does add context.

In any case, it is not really unreferred here -- if I see Link after Suggested-by, then I usually understand it is the Link to the suggestion, just like a Link after Reported-by is about the report. But, yeah, the order should be swapped.

And, of course, links should be referred when possible, i.e. I am not saying we shouldn't add references like [1] -- I try to do that all the time, but I don't see why we would want to add sentences to many commits just to re-state what the tags already say...

Quoted 2 lines

Yes, it can, but there is an assumption that any Suggested-by has to be accompanied with Acked-by (or Reviewed-by) the person who suggested something.

Not that I am aware of, i.e. someone can suggest something, and then someone else implement it, and then a maintainer applies it.

Cheers,
Miguel

#7 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 14 lines · Miguel Ojeda
Quoted 4 lines · Andy Shevchenko

IIRC Linus T. is grumpy about unreferred links (links that are need to be clicked and time potentially wasted to understand why the commit message contains them).

I didn't understand Linus' emails back then to say we shouldn't have unreferred links at all anymore and thus to have to put extra sentences in the commit. From what I recall, it was about having Links that do not add information (in particular about the msgid ones because they could be located in other ways), and the one here in the patch does add context.

Quoted 3 lines

In any case, it is not really unreferred here -- if I see Link after Suggested-by, then I usually understand it is the Link to the suggestion, just like a Link after Reported-by is about the report.

I don't. To me odd Link tags give no such a connection you have. As an independent reader I can't see it at all.

Quoted 1 line

But, yeah, the order should be swapped.

Doesn't matter. Link tag is often added by b4 in order to find the mail in the archives. That kind of Link is unreferred (as it refers to the message itself) and I understand all of those as this one. Which becomes especially confusing when there are more than a single odd Link tag...

Quoted 10 lines

And, of course, links should be referred when possible, i.e. I am not saying we shouldn't add references like [1] -- I try to do that all the time, but I don't see why we would want to add sentences to many commits just to re-state what the tags already say...

Quoted 2 lines

Yes, it can, but there is an assumption that any Suggested-by has to be accompanied with Acked-by (or Reviewed-by) the person who suggested something.

Not that I am aware of, i.e. someone can suggest something, and then someone else implement it, and then a maintainer applies it.

Strange. If you, for example, create a patch based on my mail and add my Suggestion it's kinda common sense that I may or may not Ack this, right? So, unacknowledged Suggested-by:s are meaningless.

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

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 4 lines · Andy Shevchenko

Doesn't matter. Link tag is often added by b4 in order to find the mail in the archives. That kind of Link is unreferred (as it refers to the message itself) and I understand all of those as this one. Which becomes especially confusing when there are more than a single odd Link tag...

Note that the "here's a message" links should be using patch.msgid.link to help make it clearer what they are.

#9 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

In reply to Andy Shevchenko
Quoted 3 lines · Andy Shevchenko

I don't. To me odd Link tags give no such a connection you have. As an independent reader I can't see it at all.

The connection between Reported-by and Closes/Link is documented -- in fact, it is a "should", not just a suggestion:

The tag should be
followed by a Closes: tag pointing to the report, unless the report is not available on the web. The Link: tag can be used instead of Closes:
if the patch
fixes a part of the issue(s) being reported.

The Suggested-by one isn't documented -- we could add that explicitly to clarify; I am happy to send a patch for that one.

Please note that the "followed" implies the order of tags is important, which is why I was saying they should be swapped in the case of this patch so that they are not "unreferred" anymore, as you say.

Quoted 4 lines

Doesn't matter. Link tag is often added by b4 in order to find the mail in the archives. That kind of Link is unreferred (as it refers to the message itself) and I understand all of those as this one. Which becomes especially confusing when there are more than a single odd Link tag...

As Mark says, those links that Linus was complaining about should use msgid (that was the agreement that was reached), which already disambiguates.

Quoted 3 lines

Strange. If you, for example, create a patch based on my mail and add my Suggestion it's kinda common sense that I may or may not Ack this, right? So, unacknowledged Suggested-by:s are meaningless.

No, the point of the tag is to give credit to the suggester, not to make the suggester a gatekeeper of that change or to force them to review (if that is what you mean). And nobody should blame a suggester if someone implemented it wrongly or if they misunderstood the idea...

That is why "unacknowledged Suggested-by:s" are useful (and common) -- it is to give credit so that people will send more ideas:

A Suggested-by: tag indicates that the patch idea is suggested by the person named and ensures credit to the person for the idea: if we diligently credit our idea reporters, they will, hopefully, be inspired to help us again in the future. Note, this is one of only three tags you might be able to use without explicit permission of the person named (see 'Tagging people requires permission' below for details).

For instance, I give plenty of suggestions in the list, and I don't expect people (maintainers or authors) to wait on me to use them -- at all.

There are plenty of commits in the log with such tags...

I hope that clarifies.

Cheers,
Miguel

#10 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 9 lines · Miguel Ojeda
Quoted 3 lines · Andy Shevchenko

I don't. To me odd Link tags give no such a connection you have. As an independent reader I can't see it at all.

The connection between Reported-by and Closes/Link is documented -- in fact, it is a "should", not just a suggestion:

Quoted 8 lines

The tag should be
followed by a Closes: tag pointing to the report, unless the report is not available on the web. The Link: tag can be used instead of Closes:
if the patch
fixes a part of the issue(s) being reported.

The Suggested-by one isn't documented -- we could add that explicitly to clarify; I am happy to send a patch for that one.

Please! We really need to clarify more to avoid such time-consuming discussions.

Quoted 4 lines

Please note that the "followed" implies the order of tags is important, which is why I was saying they should be swapped in the case of this patch so that they are not "unreferred" anymore, as you say.

Yes, it's fine, but Closes + Reported-by are distinct even if in a wrong order. (and even if there are 2+ of those pairs, but yes, order helps to connect).

Link is broader tag. And when unreferred it's really hard to see. Even in the above citation the Link is only allowed when the issue is fixed *partially* which means to me that the commit message should probably mention that explicitly and use _referred_ Link tag.

Quoted 8 lines
Quoted 4 lines

Doesn't matter. Link tag is often added by b4 in order to find the mail in the archives. That kind of Link is unreferred (as it refers to the message itself) and I understand all of those as this one. Which becomes especially confusing when there are more than a single odd Link tag...

As Mark says, those links that Linus was complaining about should use msgid (that was the agreement that was reached), which already disambiguates.

Right, but even though the (unreferred) Link is too broad to make connections with anything.

Quoted 8 lines
Quoted 3 lines

Strange. If you, for example, create a patch based on my mail and add my Suggestion it's kinda common sense that I may or may not Ack this, right? So, unacknowledged Suggested-by:s are meaningless.

No, the point of the tag is to give credit to the suggester, not to make the suggester a gatekeeper of that change or to force them to review (if that is what you mean). And nobody should blame a suggester if someone implemented it wrongly or if they misunderstood the idea...

No, the point is to have the same (or close enough) idea to be implemented. If the suggestion was a doctored record, how can we rely on it? It has to be acknowledged. Or at least it should need an acknowledgement.

Quoted 9 lines

That is why "unacknowledged Suggested-by:s" are useful (and common) -- it is to give credit so that people will send more ideas:

A Suggested-by: tag indicates that the patch idea is suggested by the person named and ensures credit to the person for the idea: if we diligently credit our idea reporters, they will, hopefully, be inspired to help us again in the future. Note, this is one of only three tags you might be able to use without explicit permission of the person named (see 'Tagging people requires permission' below for details).

Yes, if anybody uses *my* name for something, I really wanna check that. There were several cases when I explicitly mentioned that Suggested-by with my name was a mistake. And that's why it needs the acknowledgement.

We need to clarify this in the documentation as well.

Quoted 7 lines

For instance, I give plenty of suggestions in the list, and I don't expect people (maintainers or authors) to wait on me to use them -- at all.

There are plenty of commits in the log with such tags...

I hope that clarifies.

Not really, documentation is vague about the protocol (what tags require what kind of response and so on).

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

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 3 lines · Andy Shevchenko

Please! We really need to clarify more to avoid such time-consuming discussions.

Sounds good, will do.

Quoted 7 lines

Yes, it's fine, but Closes + Reported-by are distinct even if in a wrong order. (and even if there are 2+ of those pairs, but yes, order helps to connect).

Link is broader tag. And when unreferred it's really hard to see. Even in the above citation the Link is only allowed when the issue is fixed *partially* which means to me that the commit message should probably mention that explicitly and use _referred_ Link tag.

Hmm... I am not sure I follow or if we are disagreeing or not here.

If the issue is closed, then one uses Closes. If it is partially closed, then one uses Link. Either way, it follows the Reported-by and thus it is clear it is about the report. It is unrelated to other Link tags used by the commit message (which yes, would ideally be "referred" from the text, and ideally not placed right below that kind of tag).

If it is not obvious why the commit only partially closes it, then sure, one can add a comment in the commit message. I am not disagreeing with that (on in general with adding clarifications where needed).

Similarly, Suggested-by can be followed by a Link (the docs don't say that, but that is my suggestion, so that we can consider those also "referred").

And then there are the msgid ones which are also "referred" since they have a different domain for that purpose.

And then there are other Links, for which, yeah, I agree one should add a reference when useful (though not mandatory today, from my reading of the docs).

At the end of the day, this is about trying to confer information without repeating ourselves too much...

Quoted 3 lines

No, the point is to have the same (or close enough) idea to be implemented. If the suggestion was a doctored record, how can we rely on it? It has to be acknowledged. Or at least it should need an acknowledgement.

I don't follow what you are trying to say. The tag doesn't require permission, and thus nobody should hold you accountable for someone else's mistake.

Nobody "relies" on this tag for anything, or at least I am not understanding what you meant by "rely on it". What do you think people rely on it for?

Quoted 5 lines

Yes, if anybody uses *my* name for something, I really wanna check that. There were several cases when I explicitly mentioned that Suggested-by with my name was a mistake. And that's why it needs the acknowledgement.

We need to clarify this in the documentation as well.

That would be a change to the current policy (from my reading of the docs, at least, i.e. not just a clarification), which may be fine (and I understand it can be frustrating if someone makes a mistake with your name), but there is a cost to require permission in all cases too, i.e. it is a balance.

In any case, when someone adds such a tag, there is a chance to correct the mistake, since one should be Cc'd, plus the maintainer should also check the tags make sense when applying. But mistakes can still happen, of course.

Recommending a Link to follow the Suggested-by may reduce the number of mistakes too, which is why I was bringing it up.

Cheers,
Miguel

#12 lore raw

Re: [RFC PATCH v8 1/4] rust: io: add FallibleIoCapable

Quoted 16 lines · Miguel Ojeda
Quoted 3 lines · Andy Shevchenko

Please! We really need to clarify more to avoid such time-consuming discussions.

Sounds good, will do.

Quoted 7 lines

Yes, it's fine, but Closes + Reported-by are distinct even if in a wrong order. (and even if there are 2+ of those pairs, but yes, order helps to connect).

Link is broader tag. And when unreferred it's really hard to see. Even in the above citation the Link is only allowed when the issue is fixed *partially* which means to me that the commit message should probably mention that explicitly and use _referred_ Link tag.

Quoted 8 lines

Hmm... I am not sure I follow or if we are disagreeing or not here.

If the issue is closed, then one uses Closes. If it is partially closed, then one uses Link. Either way, it follows the Reported-by and thus it is clear it is about the report. It is unrelated to other Link tags used by the commit message (which yes, would ideally be "referred" from the text, and ideally not placed right below that kind of tag).

Yes, that's how it is documented now. But this is exactly the problem that if there are 2+ Link tags and they for some reason follow each other. Consider this example

Reported-by First Last
Link blablabla
Link foofoofoo

Which one for which? follows doesn't mean immediately follows. I think the partial fix has to be a referred Link.

Quoted 4 lines

If it is not obvious why the commit only partially closes it, then sure, one can add a comment in the commit message. I am not disagreeing with that (on in general with adding clarifications where needed).

Again, it's not clear even with a single link. Because in my mind, like we just noticed in the discussion, even message-id like Link tag at a brief view is odd. I need more energy to understand why that Link tag is in the message.

Quoted 3 lines

Similarly, Suggested-by can be followed by a Link (the docs don't say that, but that is my suggestion, so that we can consider those also "referred").

I think it's not required, but if it has some useful information *in addition to* the commit message of the patch, the referred Link can be added. Consider this example:

message 1:
(From: First Last) I suggest you to use temporary variable.

patch:
Use temporary variable for blablabla.
Suggested-by: First Last

In this case any Link tag is redundant in regard to the Suggested-by as it *does not* add anything to the commit message.

Quoted 2 lines

And then there are the msgid ones which are also "referred" since they have a different domain for that purpose.

These are the only Link tags that I consider referred by themselves.

Quoted 3 lines

And then there are other Links, for which, yeah, I agree one should add a reference when useful (though not mandatory today, from my reading of the docs).

Yes, that's what I want to.

Quoted 7 lines

At the end of the day, this is about trying to confer information without repeating ourselves too much...

Quoted 3 lines

No, the point is to have the same (or close enough) idea to be implemented. If the suggestion was a doctored record, how can we rely on it? It has to be acknowledged. Or at least it should need an acknowledgement.

Quoted 7 lines

I don't follow what you are trying to say. The tag doesn't require permission, and thus nobody should hold you accountable for someone else's mistake.

Nobody "relies" on this tag for anything, or at least I am not understanding what you meant by "rely on it". What do you think people rely on it for?

Imagine if the "suggested" idea was bad at the end, but there were no such (confirmed or acknowledged) suggestion, this will affect *my* reputation in case somebody put *my* name to that tag. This is an important nuance I think.

Quoted 11 lines
Quoted 5 lines

Yes, if anybody uses *my* name for something, I really wanna check that. There were several cases when I explicitly mentioned that Suggested-by with my name was a mistake. And that's why it needs the acknowledgement.

We need to clarify this in the documentation as well.

That would be a change to the current policy (from my reading of the docs, at least, i.e. not just a clarification), which may be fine (and I understand it can be frustrating if someone makes a mistake with your name), but there is a cost to require permission in all cases too, i.e. it is a balance.

Yes, and currently it assumes that Suggested-by person should confirm the suggestion. Currently it works "by trust" which might be abused or mistaken. In lieu of the tons of emails nowadays it's really hard to follow all of them and filter Suggested-by (yes, there are tools that may help with filtering, but still needs an additional work). My point is that for the maintainer the unconfirmed Suggested-by should be not recognized as a such.

Quoted 4 lines

In any case, when someone adds such a tag, there is a chance to correct the mistake, since one should be Cc'd, plus the maintainer should also check the tags make sense when applying. But mistakes can still happen, of course.

Right.

Quoted 2 lines

Recommending a Link to follow the Suggested-by may reduce the number of mistakes too, which is why I was bringing it up.

I'm not objecting that, but having it just to repeat what's already written in the commit message is not valuable in my opinion.

P.S. I'm truly don't know where you get so much time and energy for this discussion. Let go with documentation update rather than continue spending precious time on this.

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

RFC PATCH v8 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 layouts not represented by the Region-based view. Also provide smbus_read_word_swapped() for devices that transmit the high byte of a multi-byte value first.

Restrict these operations to I2cClient<Bound>, ensuring that bus I/O is only available while the client remains bound, and implement Sync for I2cClient<Bound> since its exposed SMBus operations serialize through the I2C core bus lock.

---
Igor reviewed this patch in v7, but since I added Sync on I2cClient<device::Bound> and updated some docs afterward, I did not carry his Reviewed-by: tag forward. Another review would be appreciated.

 rust/kernel/i2c.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 242 insertions(+), 1 deletion(-)
rust/kernel/i2c.rs +242 -1
index b4ff25c830fc..25a8fa2f6329 100644
@@ -13,8 +13,15 @@
     devres::Devres,
     driver,
     error::*,
+    io::{
+        FallibleIoCapable,
+        IoBackend,
+        IoBase,
+        Region, //
+    },
     of,
     prelude::*,
+    ptr::KnownSize,
     sync::aref::{
         ARef,
         AlwaysRefCounted, //
@@ -520,9 +527,15 @@ fn as_ref(&self) -> &device::Device<Ctx> {
 unsafe impl Send for I2cClient {}
 
 // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`
-// (i.e. `I2cClient<Normal>) are thread safe.
+// (i.e. `I2cClient<Normal>`) are thread safe.
 unsafe impl Sync for I2cClient {}
 
+// SAFETY: `I2cClient<Bound>` exposes only thread-safe `&self` operations:
+// SMBus transfers serialize via the I2C core bus lock and read only immutable
+// client fields (`adapter`, `addr`, `flags`), and dereferencing to
+// `I2cClient<Normal>` or `AsRef<Device<Bound>>` inherits their `Sync` impls.
+unsafe impl Sync for I2cClient<device::Bound> {}
+
 /// The registration of an i2c client device.
 ///
 /// This type represents the registration of a [`struct i2c_client`]. When an instance of this
@@ -573,3 +586,231 @@ 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> {
+        // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most
+        // 255 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_read_byte(reg)
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result {
+        // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most
+        // 255 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_write_byte(reg, value)
+    }
+}
+
+/// 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> {
+        // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most
+        // 254 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_read_word(reg)
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u16>, value: u16) -> Result {
+        // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most
+        // 254 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_write_word(reg, value)
+    }
+}
+
+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),
+        }
+    }
+
+    #[inline]
+    fn smbus_read_byte(&self, reg: u8) -> Result<u8> {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_read_byte_data` accepts any u8 command byte.
+        let ret = unsafe { bindings::i2c_smbus_read_byte_data(self.as_raw(), reg) };
+        to_result(ret)?;
+        Ok(ret as u8)
+    }
+
+    #[inline]
+    fn smbus_write_byte(&self, reg: u8, value: u8) -> Result {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_byte_data` accepts any u8 command byte and value.
+        let ret = unsafe { bindings::i2c_smbus_write_byte_data(self.as_raw(), reg, value) };
+        to_result(ret)
+    }
+
+    /// 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) };
+        to_result(ret)?;
+        Ok(ret as u16)
+    }
+
+    #[inline]
+    fn smbus_write_word(&self, reg: u8, value: u16) -> Result {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_word_data` accepts any u8 command byte and u16 value.
+        let ret = unsafe { bindings::i2c_smbus_write_word_data(self.as_raw(), reg, value) };
+        to_result(ret)
+    }
+
+    /// 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.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use kernel::{device::Bound, i2c::I2cClient, prelude::*};
+    ///
+    /// # fn test(client: &I2cClient<Bound>) -> Result<u16> {
+    /// // Read a word from a device that transmits its high byte first.
+    /// client.smbus_read_word_swapped(0x0c)
+    /// # }
+    /// ```
+    #[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
Tested-by on v8 2/4
#14 lore raw

Re: [RFC PATCH v8 2/4] i2c: rust: implement SMBus access via IoBackend

Quoted 290 lines · 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 layouts not represented by the Region-based view. Also provide smbus_read_word_swapped() for devices that transmit the high byte of a multi-byte value first.

Restrict these operations to I2cClient<Bound>, ensuring that bus I/O is only available while the client remains bound, and implement Sync for I2cClient<Bound> since its exposed SMBus operations serialize through the I2C core bus lock.

---
Igor reviewed this patch in v7, but since I added Sync on I2cClient<device::Bound> and updated some docs afterward, I did not carry his Reviewed-by: tag forward. Another review would be appreciated.

 rust/kernel/i2c.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 242 insertions(+), 1 deletion(-)
rust/kernel/i2c.rs +232 -1
index b4ff25c830fc..25a8fa2f6329 100644
@@ -13,8 +13,15 @@
     devres::Devres,
     driver,
     error::*,
+    io::{
+        FallibleIoCapable,
+        IoBackend,
+        IoBase,
+        Region, //
+    },
     of,
     prelude::*,
+    ptr::KnownSize,
     sync::aref::{
         ARef,
         AlwaysRefCounted, //
@@ -520,9 +527,15 @@ fn as_ref(&self) -> &device::Device<Ctx> {
 unsafe impl Send for I2cClient {}
 
 // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`
-// (i.e. `I2cClient<Normal>) are thread safe.
+// (i.e. `I2cClient<Normal>`) are thread safe.
 unsafe impl Sync for I2cClient {}
 
+// SAFETY: `I2cClient<Bound>` exposes only thread-safe `&self` operations:
+// SMBus transfers serialize via the I2C core bus lock and read only immutable
+// client fields (`adapter`, `addr`, `flags`), and dereferencing to
+// `I2cClient<Normal>` or `AsRef<Device<Bound>>` inherits their `Sync` impls.
+unsafe impl Sync for I2cClient<device::Bound> {}
+
 /// The registration of an i2c client device.
 ///
 /// This type represents the registration of a [`struct i2c_client`]. When an instance of this
@@ -573,3 +586,231 @@ 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> {
+        // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most
+        // 255 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_read_byte(reg)
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result {
+        // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most
+        // 255 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_write_byte(reg, value)
+    }
+}
+
+/// 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> {
+        // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most
+        // 254 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_read_word(reg)
+    }
+
+    #[inline]
+    fn io_try_write<'a>(view: I2cView<'a, u16>, value: u16) -> Result {
+        // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most
+        // 254 and the `as u8` cast is lossless.
+        let reg = Self::as_ptr(view).addr() as u8;
+        view.client.smbus_write_word(reg, value)
+    }
+}
+
+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),
+        }
+    }
+
+    #[inline]
+    fn smbus_read_byte(&self, reg: u8) -> Result<u8> {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_read_byte_data` accepts any u8 command byte.
+        let ret = unsafe { bindings::i2c_smbus_read_byte_data(self.as_raw(), reg) };
+        to_result(ret)?;
+        Ok(ret as u8)
+    }
+
+    #[inline]
+    fn smbus_write_byte(&self, reg: u8, value: u8) -> Result {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_byte_data` accepts any u8 command byte and value.
+        let ret = unsafe { bindings::i2c_smbus_write_byte_data(self.as_raw(), reg, value) };
+        to_result(ret)
+    }
+
+    /// 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) };
+        to_result(ret)?;
+        Ok(ret as u16)
+    }
+
+    #[inline]
+    fn smbus_write_word(&self, reg: u8, value: u16) -> Result {
+        // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client`
+        // pointer as guaranteed by the type invariant of `I2cClient`.
+        // `i2c_smbus_write_word_data` accepts any u8 command byte and u16 value.
+        let ret = unsafe { bindings::i2c_smbus_write_word_data(self.as_raw(), reg, value) };
+        to_result(ret)
+    }
+
+    /// 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.
+    ///
+    /// # Examples
+    ///
+    /// ```no_run
+    /// use kernel::{device::Bound, i2c::I2cClient, prelude::*};
+    ///

rust/kernel/i2c.rs unsafe impl Send for Registration {} · line 816

Quoted 10 lines
rust/kernel/i2c.rs +10 -0
+    /// # fn test(client: &I2cClient<Bound>) -> Result<u16> {
+    /// // Read a word from a device that transmits its high byte first.
+    /// client.smbus_read_word_swapped(0x0c)
+    /// # }
+    /// ```
+    #[inline]
+    pub fn smbus_read_word_swapped(&self, reg: u8) -> Result<u16> {
+        self.smbus_read_word(reg).map(u16::swap_bytes)
+    }
+}

Thanks
- Markus Probst

#16 lore raw

RFC PATCH v8 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. Registration is unsafe because callers must not leak the returned device (e.g. via mem::forget). It returns an owned registered device bound to the parent lifetime, whose destructor unregisters it before destroying its Rust private data and releasing the allocation reference.

Allow private data to borrow resources tied to the bound parent lifetime. This lets drivers capture bus-specific resources during probe and use them directly from subsystem callbacks without recovering them from a generic parent device.

Accept only INDIO_DIRECT_MODE. Other modes require additional state and teardown handling not provided by this initial abstraction.

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              | 519 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 4 files changed, 527 insertions(+), 2 deletions(-)
 create mode 100644 rust/kernel/iio.rs
include/linux/iio/iio.h +4 -2
index 9b63785d5aec..e2ffb2b35126 100644
@@ -450,8 +450,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 3791af0aadc7..c2e2fb32ebe3 100644
@@ -64,6 +64,8 @@
 #include <linux/fwctl.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 +519 -0

519 lines not on this page · raw message

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

Re: [RFC PATCH v8 3/4] rust: add minimal IIO subsystem abstractions

Quoted 25 lines · 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. Registration is unsafe because callers must not leak the returned device (e.g. via mem::forget). It returns an owned registered device bound to the parent lifetime, whose destructor unregisters it before destroying its Rust private data and releasing the allocation reference.

Allow private data to borrow resources tied to the bound parent lifetime. This lets drivers capture bus-specific resources during probe and use them directly from subsystem callbacks without recovering them from a generic parent device.

Accept only INDIO_DIRECT_MODE. Other modes require additional state and teardown handling not provided by this initial abstraction.

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

...

rust/bindings/bindings_helper.h line 70

Quoted 10 lines
rust/bindings/bindings_helper.h +2 -0
@@ -64,6 +64,8 @@
 #include <linux/fwctl.h>
 #include <linux/fs.h>
 #include <linux/i2c.h>
 
+#include <linux/iio/iio.h>
 
+#include <linux/iio/types.h>

No need, this is separated header, but it's rarely needed standalone. iio.h guarantees that it will provide necessary types.

Quoted 3 lines
rust/bindings/bindings_helper.h +0 -0
 #include <linux/interrupt.h>

#include <linux/io-pgtable.h>
#include <linux/ioport.h>

I would like somebody to revisit this rather cumbersome list of headers here and try to balance them for not including implied ones (yes, this is more a guesswork, but feel free to Cc Joshua Crofts and me on the discussion mail you can start with this matter).

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

RFC PATCH v8 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.

Capture a bound I2C client reference during probe and store it in the IIO private data. The registered IIO device carries the same bound lifetime, keeping the client valid throughout read_raw callbacks.

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.

Add usize bit and mask helpers for constructing the IIO channel information mask.

---
 drivers/iio/position/Kconfig   |  11 ++
 drivers/iio/position/Makefile  |   1 +
 drivers/iio/position/as5600.rs | 193 +++++++++++++++++++++++++++++++++
 rust/kernel/bits.rs            |  29 +++++
 4 files changed, 234 insertions(+)
 create mode 100644 drivers/iio/position/as5600.rs
drivers/iio/position/Kconfig +11 -0
index 1576a6380b53..7c278f82f53d 100644
@@ -6,6 +6,17 @@
 
 menu "Linear and angular position sensors"
 
+config AS5600
+	tristate "ams AS5600 magnetic rotary position sensor"
+	depends on IIO=y && 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 +193 -0

193 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
#19 lore raw

Hi,

I apologize if you have already answered this previously...

drivers/iio/position/Kconfig line 11

Quoted 11 lines · Muchamad Coirul Anwar
drivers/iio/position/Kconfig +3 -0
index 1576a6380b53..7c278f82f53d 100644
@@ -6,6 +6,17 @@
 
 menu "Linear and angular position sensors"
 
+config AS5600
+	tristate "ams AS5600 magnetic rotary position sensor"
+	depends on IIO=y && I2C=y && RUST

Why must IIO=y and I2C=y? I.e., why can't they be loadable modules?

drivers/iio/position/Kconfig line 18

Quoted 7 lines
drivers/iio/position/Kconfig +7 -0
+	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.

Thanks.

Signature · 1 line
~Randy
#20 lore raw
In reply to Muchamad Coirul Anwar
Quoted 16 lines · 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.

Capture a bound I2C client reference during probe and store it in the IIO private data. The registered IIO device carries the same bound lifetime, keeping the client valid throughout read_raw callbacks.

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.

Quoted 6 lines

Add usize bit and mask helpers for constructing the IIO channel information mask.

Again, do not put unreferred Link tags.

...

drivers/iio/position/Kconfig line 10

Quoted 1 line
drivers/iio/position/Kconfig +1 -0
+	tristate "ams AS5600 magnetic rotary position sensor"

Make this line to be the same or very similar to the top comment in the file. (or other way around)

drivers/iio/position/as5600.rs line 63

Quoted 3 lines
drivers/iio/position/as5600.rs new file +2 -0
+//! Driver for ams AS5600 12-bit magnetic rotary position sensor.
 
+    description: "I2C Driver for ams OSRAM AS5600 Magnetic Rotary Position Sensor",

Same for these.

...

drivers/iio/position/Kconfig line 11

Quoted 1 line
drivers/iio/position/Kconfig +1 -0
+	depends on IIO=y && I2C=y && RUST

Huh?!

...

drivers/iio/position/Kconfig line 15

Quoted 4 lines
drivers/iio/position/Kconfig +4 -0
+	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.

Unneeded details, what we need is something like top level parameters (12-bit, for example, that's already mentioned). Sysfs and related Linux kernel pieces are usually not being interested to the users here.

Quoted 2 lines
drivers/iio/position/Kconfig +2 -0
+	  To compile this driver as a module, choose M here: the
+	  module will be called as5600.

...

drivers/iio/position/as5600.rs line 131

Quoted 2 lines
drivers/iio/position/as5600.rs new file +2 -0
+            // Scale factor: radians per LSB = 2*pi / 4096 ~= 0.001533981
+            IioChanInfo::Scale => Ok(IioVal::IntPlusNano(0, 1533981)),

Please try to provide calculations based on the proper constants, use PI constant (for now open coded) with desired precision and shift it right by log2(2048). I believe you want 9-sign (yes, 9 in the fraction part) PI == 3141592654 (or ...53 if mentioned in the datasheet).

Signature · 2 lines
With Best Regards,
Andy Shevchenko