iio: position: add Rust driver for ams AS5600
Subsystems (5)
v4 cover iio: position: add Rust driver for ams AS5600
This is v4 of the Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. v3 hardened the IIO abstraction layer and introduced kernel synchronisation primitives. This revision simplifies the driver substantially based on review feedback, removes components that were over-engineered for a single-bus 12-bit sensor, and validates the result with comprehensive hardware testing.
Apologies for the delay.
Changes since RFC v3:
IIO abstraction (rust/kernel/iio.rs):
- Removed DirectModeGuard entirely (struct, C helpers, binding file) per Jonathan's review of patch 2. This driver operates in INDIO_DIRECT_MODE only and has no buffer or trigger support, so claiming direct mode is redundant. If buffer support is added later, the guard can be reintroduced at the driver level rather than the trampoline.
- Deleted rust/helpers/iio.c (no remaining consumers).
- Fixed SAFETY comment: iio_device_alloc uses kzalloc internally, so priv_ points to zeroed memory, not uninitialised memory as the previous comment stated.
- Added i32::try_from(size_of::<T>()) guard to prevent silent truncation when passing priv_size to iio_device_alloc.
- No other functional changes to the abstraction.
I2C abstraction (rust/kernel/i2c.rs):
- Provided full io_read/io_write method bodies for IoCapable<u8> and IoCapable<u16> per Brandon's note that IoCapable is no longer a marker trait on current tree. The empty impls from v3 would not compile.
- Added clarifying comment on maxsize(): this is the SMBus command
byte range (0x00-0xFF), not the 7-bit I2C device address.
Driver (drivers/iio/position/as5600.rs):
- Removed circuit breaker (DeviceState enum, handle_io_error) per Jonathan's review of patch 3. The AS5600 sits on a short local bus with no hot-plug; if the bus fails, propagating the error directly is simpler and more predictable than internal state machines.
- Replaced As5600Io(*mut i2c_client) with ARef<I2cClient> per Brandon's suggestion. This eliminates manual unsafe Send/Sync impls; ARef provides proper reference counting and the compiler can verify the bounds itself.
- Removed the generic type parameter from As5600Priv and As5600HwState per Brandon's feedback. A concrete type is sufficient for a single-bus sensor.
- Moved channel spec from KBox<[iio_chan_spec; 1]> (heap) to a module- level static per Jonathan's review of patch 2, matching what all C IIO drivers do and eliminating the KBox lifetime concern noted in v3.
- Replaced two sequential try_read8 calls (high byte + low byte) with a single try_read16 word read followed by swap_bytes() per Jonathan's review of patch 3. The AS5600 stores angle big-endian across 0x0C-0x0D; SMBus word reads return little-endian, so a byte swap recovers the correct value.
In my v3 reply I said I would use i2c_smbus_read_word_swapped. I apologise for not following through. Adding a standalone swapped method alongside the Io trait felt premature while the question of whether this driver should use regmap-rs instead remains open. For this RFC with a single word read, the in-driver swap is retained with a TODO comment. Happy to add the wrapper in v5 if preferred.
- Added AS5600_RAW_ANGLE_MASK via genmask_u16(0..=11) for 12-bit angle extraction.
- Updated datasheet URL to ams-osram.com per Brandon's note (old link broken).
- Added depends on IIO to Kconfig (won't link without it).
- Kconfig and Makefile entries merged into driver patch per Jonathan's review of patch 4.
Known limitations (to be addressed before mainline):
- No power management (suspend/resume) hooks.
- write_raw and buffer/trigger support deferred to future work.
- No i2c_smbus_read_word_swapped wrapper yet (see above).
Changes since RFC v2:
(see v3 cover letter for full changelog)
Changes since RFC v1:
- Moved magnet validation from probe() to read_raw().
- Added minimal Rust IIO abstractions.
- Added OF device table for devicetree matching.
Design notes:
The IIO abstraction does NOT use devres (devm_iio_device_alloc). The Rust Drop implementation controls the cleanup sequence directly:
iio_device_unregister -> drop_in_place(T) -> iio_device_free. This avoids ordering conflicts between Rust ownership semantics and the C devres teardown sequence.
Module ownership is enforced via the second parameter of __iio_device_register(indio_dev, module), not via iio_info.owner.
Muchamad Coirul Anwar (3):
i2c: rust: implement SMBus read abstraction via kernel::io::Io for
I2cClient
rust: add minimal IIO subsystem abstractions
iio: position: add Rust driver for ams AS5600
drivers/iio/position/Kconfig | 14 ++ drivers/iio/position/Makefile | 1 + drivers/iio/position/as5600.rs | 181 ++++++++++++++++++++ rust/bindings/bindings_helper.h | 2 + rust/kernel/error.rs | 1 + rust/kernel/i2c.rs | 89 ++++++++++ rust/kernel/iio.rs | 295 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 8 files changed, 585 insertions(+) create mode 100644 drivers/iio/position/as5600.rs create mode 100644 rust/kernel/iio.rs
---
Tested on BeagleBone Black (AM335x), kernel 7.1.0-g97e88f52769a (build 88), AS5600 on i2c-2 (0x36) at 3.3V, 6mm diametric neodymium magnet. Full test session: 2026-06-30 12:00 UTC.
Build: make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- modules
(zero warnings, zero errors)
Module size: 15108 bytes (as5600.ko)
Functional tests:
1. Probe and registration:
$ sudo insmod as5600.ko
$ echo "as5600 0x36" > /sys/bus/i2c/devices/i2c-2/new_device
$ cat /sys/bus/iio/devices/iio:device0/name
as5600
$ ls /sys/bus/i2c/devices/2-0036/driver
2-0036 bind module uevent unbind2. Raw angle and scale (magnet present, rotated by hand):
$ cat /sys/bus/iio/devices/iio:device0/in_angl_raw
233
$ cat /sys/bus/iio/devices/iio:device0/in_angl_scale
0.001533981
Multiple reads while rotating: 233, 898, 1873, 1543, 468, 63, 252
All values within expected 0-4095 range (12-bit).
Computed: 898 * 0.001533981 = 1.378 rad, about 78.9 degrees. 3. Magnet removed (MD bit clear, error propagation without circuit breaker):
$ cat /sys/bus/iio/devices/iio:device0/in_angl_raw
cat: '/sys/.../in_angl_raw': No data available Driver reads STATUS, finds MD=0, returns -ENODATA directly. No internal state machine. Next read with magnet present succeeds immediately without recovery sequence.
4. Unbind/rebind lifecycle (PinnedDrop with ARef cleanup):
$ echo "2-0036" > /sys/bus/i2c/devices/2-0036/driver/unbind
$ ls /sys/bus/iio/devices/iio:device0
ls: cannot access '...': No such file or directory
$ echo "2-0036" > /sys/bus/i2c/drivers/as5600/bind
dmesg confirms full PinnedDrop sequence on unbind:
iio_device_unregister -> drop_in_place(Mutex<ARef>) -> iio_device_free
Re-probe succeeds, device functional again.
$ dmesg | grep -i "oops\|panic\|bug:"
(empty)5. Concurrent stress (Mutex serialization under contention):
$ for i in $(seq 1 10); do
timeout 10 sh -c 'while true; do
cat .../in_angl_raw > /dev/null 2>&1; done' &
done; wait
10 parallel readers hammering in_angl_raw for 10 seconds.
All workers exit cleanly via timeout (exit 124).
Repeated 3 times, same result each time.
$ dmesg | grep -i "oops\|panic\|bug:\|rcu"
(empty, only boot-time RCU init messages present)
No corrupted values, no races, no use-after-free. 6. Unbind/rebind race (concurrent I/O during device removal):
Terminal 1: continuous cat .../in_angl_raw in background Terminal 2: 20x unbind/bind cycle with 100ms sleep between This exercises the iio_device_unregister drain path. The IIO core waits for in-flight read_raw callbacks to complete before PinnedDrop proceeds with drop_in_place.
$ dmesg | grep -i "oops\|panic\|bug:"
(empty, all 20 cycles complete without crash)
7. Lifecycle stress (20x probe/remove under I/O load):
20 complete insmod/new_device/delete_device/rmmod cycles with 10 concurrent readers active during each cycle. Each cycle allocates a new iio_dev (confirmed by unique indio_dev addresses in dmesg) and frees it via PinnedDrop. No memory leaks, no KASAN reports, no dangling pointers.
Signature · 1 line
2.50.0
RFC PATCH v4 1/3 i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Implement the Io trait for I2cClient, providing SMBus byte and word read/write operations with automatic offset validation via io_addr().
I2cClient implements the generic Io trait rather than exposing standalone SMBus methods, following the direction established in [1] and [2]. The underlying calls are still i2c_smbus_read_byte_data and i2c_smbus_read_word_data.
I2cClient now implements IoCapable<u8> and IoCapable<u16> with maxsize=256 (SMBus command byte range 0x00-0xFF, not the 7-bit device address which is handled by the I2C core at adapter level).
--- rust/kernel/i2c.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+)
rust/kernel/i2c.rs +89 -0
@@ -14,6 +14,7 @@ devres::Devres, driver, error::*, + io::{Io, IoCapable}, of, prelude::*, sync::aref::{
@@ -601,3 +602,91 @@ 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 {} + +impl <Ctx : device::DeviceContext >IoCapable <u8 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u8 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer +// (type invariant). `address` was pre-validated by io_addr() before +// this function is called (trait contract). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. This is only called via try_read() which +// first validates bounds via io_addr(). For I2C, the caller should +// always use try_read8() which provides proper error handling. + retas u8 + } + +unsafe fn io_write (&self, value:u8 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_byte_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. `IoCapable` trait signature does not +// support error returns. Use with caution. + } +} + +impl <Ctx : device::DeviceContext >IoCapable <u16 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u16 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. See u8 implementation note. + retas u16 + } + +unsafe fn io_write (&self, value:u16 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_word_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. + } +} + +impl <Ctx : device::DeviceContext >Io for I2cClient <Ctx > { +#[inline] +fn addr (&self) ->usize { +0 + } + +/// SMBus command byte range: 0x00-0xFF (256 possible register addresses). +/// This is NOT the 7-bit device address; that is handled by the I2C core. +#[inline] +fn maxsize (&self) ->usize { +256 + } + +#[inline] +fn try_read8 (&self, offset:usize ) ->Result <u8 > +where +Self :IoCapable <u8 >, + { +let reg = self.io_addr ::<u8 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 1 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u8 ) + } + } + +#[inline] +fn try_read16 (&self, offset:usize ) ->Result <u16 > +where +Self :IoCapable <u16 >, + { +let reg = self.io_addr ::<u16 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 2 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u16 ) + } + } +}
Signature · 1 line
2.50.0
Igor Korotin
maintainerRe: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Thanks for reworking this to use Io as agreed -- the direction is right. But I think the fix is incomplete, and it points at something I'd like Danilo's take on.
try_read8()/try_read16() are overridden here with real errno handling, bypassing IoCapable::io_read entirely -- necessary, since io_read's signature (-> T, not Result<T>) can't carry a negative errno from i2c_smbus_read_byte_data.
But that override only covers two of Io's entry points. The generic try_read<T, L>, try_write<T, L>, try_update<T, L, F>, and try_write_reg all still route straight through IoCapable::io_read/io_write and aren't overridden here. Concretely:
- client.try_read::<u8, _>(offset) (as opposed to try_read8()) silently casts a negative errno to a garbage u8 on failure -- the exact bug try_read8() exists to avoid, reachable through a different, still-public method on the same type.
- try_write8()/try_write16() aren't overridden at all, so any write through them (or the generic try_write) discards the real SMBus return value and reports Ok(()) even when the transaction failed on the bus (NACK, arbitration loss, timeout).
- try_update() combines both problems in a single read-modify-write.
This driver only calls try_read8()/try_read16(), so AS5600 itself isn't affected in practice. But the abstraction being introduced here would be unsound the moment any write-capable consumer reaches for it -- and I don't think patching try_write8/try_update one at a time is the right fix, since it just leaves the same trap for whichever method nobody's gotten around to overriding yet.
Danilo -- since using Io for I2C was originally your suggestion, I'd like your read on this before we go further: IoCapable::io_read/io_write are infallible by signature, which holds for MMIO/PCI-config (bounds-checked implies success) but doesn't hold for a bus transaction -- I2C can genuinely fail per-transfer regardless of address validity. Given that, is Io/IoCapable the right abstraction for I2cClient to implement at all, or does I2C need its own fallible-native interface rather than overriding pieces of this one?
Cheers
Igor
Danilo Krummrich
maintainerRe: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 3 lines · Igor Korotin
Thanks for reworking this to use
Ioas agreed -- the direction is right. But I think the fix is incomplete, and it points at something I'd like Danilo's take on.
The reason this should go through the generic I/O backend infrastructure is that we want this to be able take advantage of the register!() framework.
You are right that currently fallible I/O is not supported. However, this should easily be fixable by rebasing on top of the latest I/O work [1], plus the adjustments in [2].
With this, the posted code becomes something like this:
pub struct I2cBackend;
pub struct I2cView<'a, T: ?Sized> {
client: &'a I2cClient<Bound>,
ptr: *mut T,
}
impl<T: ?Sized> Copy for I2cView<'_, T> {}
impl<T: ?Sized> Clone for I2cView<'_, T> { ... }
impl IoBackend for I2cBackend {
type View<'a, T: ?Sized + KnownSize> = I2cView<'a, T>;
fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut T {
view.ptr // fake pointer for the register offset
}
unsafe fn project_view<'a, T, U>(
view: Self::View<'a, T>,
ptr: *mut U,
) -> Self::View<'a, U> {
I2cView { client: view.client, ptr }
}
}
impl FallibleIoCapable<u8> for I2cBackend {
fn io_try_read<'a>(view: I2cView<'a, u8>) -> Result<u8> {
...
view.client.smbus_read_byte_data(offset)
}
fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result {
...
view.client.smbus_write_byte_data(offset, value)
}
}[1] https://lore.kernel.org/driver-core/[email protected]/
[2] FallibleIoCapable:
rust/kernel/io.rs +46 -19
@@ -275,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`.
@@ -644,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) }
@@ -654,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) }
@@ -664,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) }
@@ -674,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) }
@@ -684,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) }
@@ -694,7 +725,7 @@ fn try_write8(self, value: u8, offset: usize) -> Resultfn 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) }
@@ -704,7 +735,7 @@ fn try_write16(self, value: u16, offset: usize) -> Resultfn 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) }
@@ -714,7 +745,7 @@ fn try_write32(self, value: u32, offset: usize) -> Resultfn 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) }
@@ -826,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.
@@ -859,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.
@@ -904,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 ();
@@ -937,16 +967,14 @@ fn try_write_reg<T, L, V>(self, value: V) -> Resultfn 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.
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
In reply to Igor KorotinQuoted 7 lines · Igor Korotin
This driver only calls try_read8()/try_read16(), so AS5600 itself isn't affected in practice. But the abstraction being introduced here would be unsound the moment any write-capable consumer reaches for it -- and I don't think patching try_write8/try_update one at a time is the right fix, since it just leaves the same trap for whichever method nobody's gotten around to overriding yet.
Quoted 8 lines
Danilo -- since using Io for I2C was originally your suggestion, I'd like your read on this before we go further: IoCapable::io_read/io_write are infallible by signature, which holds for MMIO/PCI-config (bounds-checked implies success) but doesn't hold for a bus transaction -- I2C can genuinely fail per-transfer regardless of address validity. Given that, is Io/IoCapable the right abstraction for I2cClient to implement at all, or does I2C need its own fallible-native interface rather than overriding pieces of this one?
Agreed. I will rework on top of Danilo's FallibleIoCapable approach in v5. I checked rust-next and neither FallibleIoCapable nor io_projection v6 has landed yet.
Danilo, should I wait for io_projection to land first before rebasing, or should I carry FallibleIoCapable as a preparatory patch in my series?
Thanks for the detailed review.
Coirul
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 2 lines · Muchamad Coirul Anwar
Agreed. I will rework on top of Danilo's FallibleIoCapable approach in v5.
For the write side of that rework: I recently posted an RFC with a Rust port of the SMB347 charger driver [1], which Igor pointed at this series (thanks). I'm dropping my standalone SMBus helpers in favor of your Io-based approach.
The SMB347 driver may be a useful early consumer for v5: unlike the AS5600 it writes -- a config-unlock write plus read-modify-write updates of charge-control register fields -- so it would exercise the io_try_write/try_update paths that Igor noted are otherwise easy to leave silently infallible. NACK and arbitration loss on a charger config write are exactly the failures you don't want reported as Ok(()).
Happy to rebase it onto v5 when it's out and report back.
Bruce
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 13 lines · Bruce Robertson
For the write side of that rework: I recently posted an RFC with a Rust port of the SMB347 charger driver [1], which Igor pointed at this series (thanks). I'm dropping my standalone SMBus helpers in favor of your Io-based approach.
The SMB347 driver may be a useful early consumer for v5: unlike the AS5600 it writes -- a config-unlock write plus read-modify-write updates of charge-control register fields -- so it would exercise the io_try_write/try_update paths that Igor noted are otherwise easy to leave silently infallible. NACK and arbitration loss on a charger config write are exactly the failures you don't want reported as Ok(()).
Quoted 1 line
Happy to rebase it onto v5 when it's out and report back.
Thanks Bruce. Good to know the SMB347 port can benefit from this too. The extra write-side coverage would really help, since the AS5600 only reads. I will CC you on v5.
Coirul
Danilo Krummrich
maintainerRe: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
In reply to Muchamad Coirul AnwarQuoted 3 lines · Muchamad Coirul Anwar
Agreed. I will rework on top of Danilo's FallibleIoCapable approach in v5. I checked rust-next and neither FallibleIoCapable nor
io_projectionv6 has landed yet.
The patch series is merged in driver-core-next [1]. You can check the MAINTAINERS file to see how patches for certain subsystems, components and drivers are usually routed.
If unsure you can also check the linux-next integration tree [2] which merges all development trees in a daily effort.
Quoted 2 lines
Danilo, should I wait for
io_projectionto land first before rebasing, or should I carry FallibleIoCapable as a preparatory patch in my series?
As mentioned, I/O projections did land already. Regarding the FallibleIoCapable change, please feel free to pick up the diff I posted and send it as a prerequisite patch in your series.
Thanks,
Danilo
[1] https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git/log/?h=driver-core-next
[2] https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 7 lines · Danilo Krummrich
The patch series is merged in driver-core-next [1]. You can check the
MAINTAINERSfile to see how patches for certain subsystems, components and drivers are usually routed.If unsure you can also check the linux-next integration tree [2] which merges all development trees in a daily effort.
Quoted 6 lines
As mentioned, I/O projections did land already. Regarding the FallibleIoCapable change, please feel free to pick up the diff I posted and send it as a prerequisite patch in your series.
[1] https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git/log/?h=driver-core-next
[2] https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/
Thanks Danilo. I will rebase on driver-core-next and carry FallibleIoCapable as a prerequisite patch in v5.
Coirul
Danilo Krummrich
maintainerRe: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
In reply to Muchamad Coirul AnwarQuoted 1 line · Muchamad Coirul Anwar
+impl<Ctx:
device::DeviceContext> IoCapable<u8> for I2cClient<Ctx> {
Independent from [1], this must not be implemented for any DeviceContext. I/O operations require at least the Bound the device context.
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 7 lines · Danilo Krummrich
Quoted 1 line · Muchamad Coirul Anwar
+impl<Ctx:
device::DeviceContext> IoCapable<u8> for I2cClient<Ctx> {Independent from [1], this must not be implemented for any DeviceContext. I/O operations require at least the Bound the device context.
Understood. I will restrict to I2cClient<Bound> in v5.
Thanks
Coirul
Jonathan Cameron
maintainerRe: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
In reply to Muchamad Coirul AnwarQuoted 8 lines · On Tue, 7 Jul 2026 22:15:40 +0700 Muchamad Coirul Anwar…
Implement the Io trait for I2cClient, providing SMBus byte and word read/write operations with automatic offset validation via
io_addr().I2cClient implements the generic Io trait rather than exposing standalone SMBus methods, following the direction established in [1] and [2]. The underlying calls are still
i2c_smbus_read_byte_dataandi2c_smbus_read_word_data.
Quoted 7 lines
I2cClient now implements IoCapable<u8> and IoCapable<u16> with maxsize=256 (SMBus command byte range 0x00-0xFF, not the 7-bit device address which is handled by the I2C core at adapter level).
Just to make sure it doesn't get lost across versions - I'll repeat briefly what concerns me here. I'm also interested to hear Wolfram's view on this as well as Wolfram has probably seen more weird i2c devices than anyone else.
I2C isn't one nice set of here is how you read a byte and here is how you read a u16. Even smbus effectively has 2 options given the large number of devices with the bytes flipped. Those exist because they weren't designed against the smbus spec (very few datasheets even mention smbus) but rather the less constrained definitions of the i2c spec and under that there is no concept of a word so ordering is whatever the hardware fancies (wonderfully we even have devices that aren't consistent in ordering register pairs but let's ignore those).
So maybe introduce this as smbus as long as we can chase it with smbus_swapped for the byte swapped version. Or don't introduce smbus at all because if this limited subset of smbus applies, then maybe just jumping directly to regmap is the right way to go.
Calling this i2c and provide these interfaces is to me giving the wrong impressions of what it is.
Jonathan
Quoted 108 lines
--- rust/kernel/i2c.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+)rust/kernel/i2c.rs +89
-0@@ -14,6 +14,7 @@ devres::Devres, driver, error::*, + io::{Io, IoCapable}, of, prelude::*, sync::aref::{@@ -601,3 +602,91 @@ 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 {} + +impl <Ctx : device::DeviceContext >IoCapable <u8 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u8 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer +// (type invariant). `address` was pre-validated by io_addr() before +// this function is called (trait contract). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. This is only called via try_read() which +// first validates bounds via io_addr(). For I2C, the caller should +// always use try_read8() which provides proper error handling. + retas u8 + } + +unsafe fn io_write (&self, value:u8 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_byte_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. `IoCapable` trait signature does not +// support error returns. Use with caution. + } +} + +impl <Ctx : device::DeviceContext >IoCapable <u16 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u16 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. See u8 implementation note. + retas u16 + } + +unsafe fn io_write (&self, value:u16 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_word_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. + } +} + +impl <Ctx : device::DeviceContext >Io for I2cClient <Ctx > { +#[inline] +fn addr (&self) ->usize { +0 + } + +/// SMBus command byte range: 0x00-0xFF (256 possible register addresses). +/// This is NOT the 7-bit device address; that is handled by the I2C core. +#[inline] +fn maxsize (&self) ->usize { +256 + } + +#[inline] +fn try_read8 (&self, offset:usize ) ->Result <u8 > +where +Self :IoCapable <u8 >, + { +let reg = self.io_addr ::<u8 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 1 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u8 ) + } + } + +#[inline] +fn try_read16 (&self, offset:usize ) ->Result <u16 > +where +Self :IoCapable <u16 >, + { +let reg = self.io_addr ::<u16 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 2 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u16 ) + } + } +}
Re: [RFC PATCH v4 1/3] i2c: rust: implement SMBus read abstraction via kernel::io::Io for I2cClient
Quoted 17 lines · Jonathan Cameron
Quoted 11 lines
Implement the Io trait for I2cClient, providing SMBus byte and word read/write operations with automatic offset validation via
io_addr().I2cClient implements the generic Io trait rather than exposing standalone SMBus methods, following the direction established in [1] and [2]. The underlying calls are still
i2c_smbus_read_byte_dataandi2c_smbus_read_word_data.I2cClient now implements IoCapable<u8> and IoCapable<u16> with maxsize=256 (SMBus command byte range 0x00-0xFF, not the 7-bit device address which is handled by the I2C core at adapter level).
Just to make sure it doesn't get lost across versions - I'll repeat briefly what concerns me here. I'm also interested to hear Wolfram's view on this as well as Wolfram has probably seen more weird i2c devices than anyone else.
Quoted 8 lines
I2C isn't one nice set of here is how you read a byte and here is how you read a u16. Even smbus effectively has 2 options given the large number of devices with the bytes flipped. Those exist because they weren't designed against the smbus spec (very few datasheets even mention smbus) but rather the less constrained definitions of the i2c spec and under that there is no concept of a word so ordering is whatever the hardware fancies (wonderfully we even have devices that aren't consistent in ordering register pairs but let's ignore those).
Thanks for the feedback, Jonathan.
That's a fair point on naming. The underlying calls are i2c_smbus_read_word_data and i2c_smbus_write_word_data, so the interface really is SMBus, not raw I2C.
On smbus_swapped, AS5600 is actually big-endian and currently I handle swap_bytes() manually in the driver as a workaround. The reason I didn't add a swapped variant yet is that in v4, the I2C bindings still followed the MMIO pattern (IoCapable), which is infallible. Adding smbus_swapped on top of that felt premature when the foundation itself wasn't right for a bus that can NACK or timeout.
Quoted 7 lines
So maybe introduce this as smbus as long as we can chase it with
smbus_swappedfor the byte swapped version. Or don't introduce smbus at all because if this limited subset of smbus applies, then maybe just jumping directly to regmap is the right way to go.Calling this i2c and provide these interfaces is to me giving the wrong impressions of what it is.
In v5 I switched to FallibleIoCapable, which was proposed by Danilo specifically for fallible transports like I2C. With that foundation in place, adding a smbus_swapped backend is straightforward and I can include it in this version if that's the preferred direction.
Wolfram is on the CC list. He's no longer listed as I2C subsystem maintainer in MAINTAINERS (that's now Andi Shyti) but I agree his experience with I2C devices would be valuable here.
On regmap, I noted in the driver comment that regmap-rs with val_format_endian=Big would handle the endianness more cleanly. That would be the better path if the Rust bindings exist or are close. Since they don't yet, I went with the SMBus approach as a practical stepping stone. Happy to revisit once regmap-rs is available.
Coirul
Quoted 109 lines
Quoted 108 lines
--- rust/kernel/i2c.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+)rust/kernel/i2c.rs +89
-0@@ -14,6 +14,7 @@ devres::Devres, driver, error::*, + io::{Io, IoCapable}, of, prelude::*, sync::aref::{@@ -601,3 +602,91 @@ 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 {} + +impl <Ctx : device::DeviceContext >IoCapable <u8 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u8 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer +// (type invariant). `address` was pre-validated by io_addr() before +// this function is called (trait contract). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. This is only called via try_read() which +// first validates bounds via io_addr(). For I2C, the caller should +// always use try_read8() which provides proper error handling. + retas u8 + } + +unsafe fn io_write (&self, value:u8 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_byte_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. `IoCapable` trait signature does not +// support error returns. Use with caution. + } +} + +impl <Ctx : device::DeviceContext >IoCapable <u16 >for I2cClient <Ctx > { +unsafe fn io_read (&self, address:usize ) ->u16 { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), addressas u8 ) }; + +// NOTE: Error is lost here. See u8 implementation note. + retas u16 + } + +unsafe fn io_write (&self, value:u16 , address:usize ) { +// SAFETY: `self.as_raw()` returns a valid `struct i2c_client` pointer. +// `address` pre-validated by io_addr(). +unsafe { bindings::i2c_smbus_write_word_data (self.as_raw (), addressas u8 , value) }; +// NOTE: Return value is ignored. + } +} + +impl <Ctx : device::DeviceContext >Io for I2cClient <Ctx > { +#[inline] +fn addr (&self) ->usize { +0 + } + +/// SMBus command byte range: 0x00-0xFF (256 possible register addresses). +/// This is NOT the 7-bit device address; that is handled by the I2C core. +#[inline] +fn maxsize (&self) ->usize { +256 + } + +#[inline] +fn try_read8 (&self, offset:usize ) ->Result <u8 > +where +Self :IoCapable <u8 >, + { +let reg = self.io_addr ::<u8 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 1 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_byte_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u8 ) + } + } + +#[inline] +fn try_read16 (&self, offset:usize ) ->Result <u16 > +where +Self :IoCapable <u16 >, + { +let reg = self.io_addr ::<u16 >(offset)?as u8 ; +// SAFETY: `self.as_raw()` returns a valid pointer to a `struct i2c_client` +// as guaranteed by the type invariant of `I2cClient`. `reg` is bounds-checked +// by `io_addr()` above (offset + 2 <= 256). +let ret =unsafe { bindings::i2c_smbus_read_word_data (self.as_raw (), reg) }; +if ret <0 { +Err (Error ::from_errno (ret)) + }else { +Ok (retas u16 ) + } + } +}
RFC PATCH v4 2/3 rust: add minimal IIO subsystem abstractions
In reply to Muchamad Coirul AnwarAdd safe Rust wrappers for the Linux IIO (Industrial I/O) subsystem:
- IioVal enum with NonZeroI32 for division-by-zero prevention on IIO_VAL_FRACTIONAL
- IioDriver trait with read_raw callback (requires Send + Sync)
- Device<T, State> with typestate (Unregistered -> Registered) to prevent double-registration at compile time
- PinnedDrop for guaranteed cleanup: iio_device_unregister -> drop_in_place(T) -> iio_device_free
- Compile-time const VTABLE (iio_info)
- C-to-Rust FFI trampoline for read_raw dispatch
The abstraction uses iio_device_alloc (not devm_*) so that the Rust Drop implementation has full control over the cleanup sequence. Module ownership is enforced via __iio_device_register(indio_dev, module).
--- rust/bindings/bindings_helper.h | 2 + rust/kernel/error.rs | 1 + rust/kernel/iio.rs | 293 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 298 insertions(+) create mode 100644 rust/kernel/iio.rs
rust/bindings/bindings_helper.h +2 -0
@@ -61,6 +61,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/error.rs +1 -0
@@ -86,6 +86,7 @@ macro_rules! declare_err {declare_err! (EIOCBQUEUED ,"iocb queued, will get completion event." );declare_err! (ERECALLCONFLICT ,"Conflict with recalled state." );declare_err! (ENOGRACE ,"NFS file lock reclaim refused." ); +declare_err! (ENODATA ,"No data available." ); }/// Generic integer kernel error.
rust/kernel/iio.rs new file +293 -0
293 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -78,6 +78,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
Danilo Krummrich
maintainerRe: [RFC PATCH v4 2/3] rust: add minimal IIO subsystem abstractions
Quoted 1 line · Muchamad Coirul Anwar
Add safe Rust wrappers for the Linux IIO (Industrial I/O) subsystem:
Does IIO's iio_device_unregister() synchronize against in-flight IOCTLs?
Re: [RFC PATCH v4 2/3] rust: add minimal IIO subsystem abstractions
Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Muchamad Coirul Anwar
Add safe Rust wrappers for the Linux IIO (Industrial I/O) subsystem:
Does IIO's
iio_device_unregister()synchronize against in-flight IOCTLs?
From what I traced, yes. iio_device_unregister goes through cdev_device_del, device_del, sysfs_remove_dir, and ends up in kernfs_drain which waits for active sysfs readers to finish. Please correct me if I'm missing something here.
Thanks
Coirul
Jonathan Cameron
maintainerRe: [RFC PATCH v4 2/3] rust: add minimal IIO subsystem abstractions
Quoted 12 lines · On Tue, 14 Jul 2026 23:20:48 +0700 Muchamad Coirul Anwar…
Quoted 5 lines · Danilo Krummrich
Quoted 1 line · Muchamad Coirul Anwar
Add safe Rust wrappers for the Linux IIO (Industrial I/O) subsystem:
Does IIO's
iio_device_unregister()synchronize against in-flight IOCTLs?From what I traced, yes.
iio_device_unregistergoes throughcdev_device_del,device_del,sysfs_remove_dir, and ends up inkernfs_drainwhich waits for active sysfs readers to finish. Please correct me if I'm missing something here.
That covers sysfs, but IIO has a bunch of chrdevs (though you aren't using them here). I'd go for 'almost certainly' for whether synchronizes in all cases but we have found one or two races over the years.
The way it is supposed to work is that the unregister takes the info_exist_lock and sets the iio_dev->info pointer to NULL. It also wakes up any one polling etc, and returns errors on all in flight actions. Every ioctl takes that same lock and checks if info is null before carrying on. The lock is held across the ioctl to stop any racing with the unregister path.
I can't recall any recent paths being discovered where the lock + check was missed but we did have them in the past, though normally not about IOCTLs but about in kernel consumer drivers.
There is an outstanding fix related to those, and read_avail
+ lifetimes if people allocate storage in that callback but I doubt this goes anywhere near that area of IIO yet.
Jonathan
Quoted 2 lines
Thanks
Coirul
Re: [RFC PATCH v4 2/3] rust: add minimal IIO subsystem abstractions
Quoted 17 lines · Jonathan Cameron
Quoted 5 lines
From what I traced, yes.
iio_device_unregistergoes throughcdev_device_del,device_del,sysfs_remove_dir, and ends up inkernfs_drainwhich waits for active sysfs readers to finish. Please correct me if I'm missing something here.That covers sysfs, but IIO has a bunch of chrdevs (though you aren't using them here). I'd go for 'almost certainly' for whether synchronizes in all cases but we have found one or two races over the years.
The way it is supposed to work is that the unregister takes the
info_exist_lockand sets theiio_dev->infopointer to NULL. It also wakes up any one polling etc, and returns errors on all in flight actions. Every ioctl takes that same lock and checks if info is null before carrying on. The lock is held across the ioctl to stop any racing with the unregister path.
Quoted 7 lines
I can't recall any recent paths being discovered where the lock + check was missed but we did have them in the past, though normally not about IOCTLs but about in kernel consumer drivers.
There is an outstanding fix related to those, and
read_avail
+ lifetimes if people allocate storage in that callback but I doubt this goes anywhere near that area of IIO yet.
Thanks, Jonathan.
The lock+check mechanism makes sense. AS5600 only implements read_raw and doesn't use chrdevs or allocate storage in callbacks, so it should be safe from the race you mentioned.
I will fix the SAFETY comment in iio.rs. The current wording is too broad, so I'll narrow it down to describe the two separate sync paths (kernfs_drain vs info_exist_lock).
Coirul
RFC PATCH v4 3/3 iio: position: add Rust driver for ams AS5600
In reply to Muchamad Coirul AnwarAdd a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. The driver exposes in_angl_raw and in_angl_scale via the IIO sysfs interface.
Features:
- ARef<I2cClient> for safe refcounted I2C client access
- Mutex-serialized status + angle read sequence
- Static channel spec (module-level const)
- No magnet validation at probe (deferred to read_raw per IIO convention)
- Error propagation via ? operator (no recovery state machine)
The byte order for the AS5600's big-endian registers is handled via swap_bytes() in-driver. This is equivalent to C's i2c_smbus_read_word_swapped(). The long-term solution is regmap-rs where endianness is configured once at the transport level.
Tested on BeagleBone Black (AM335x) with AS5600 on i2c-2 (0x36).
--- drivers/iio/position/Kconfig | 14 +++ drivers/iio/position/Makefile | 1 + drivers/iio/position/as5600.rs | 181 +++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 drivers/iio/position/as5600.rs
drivers/iio/position/Kconfig +14 -0
@@ -6,6 +6,20 @@ menu "Linear and angular position sensors" +config AS5600 + tristate "ams AS5600 magnetic rotary position sensor" + depends on I2C && IIO && RUST + help + Say Y here to build support for the ams AS5600 12-bit + magnetic rotary position sensor with IIO channel support + (in_angl_raw and in_angl_scale). + + This is a Rust driver that exposes the 12-bit raw angle + and radian scale via the IIO subsystem. + + 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
@@ -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 +181 -0
181 lines not on this page · raw message
Signature · 1 line
2.50.0
Jonathan Cameron
maintainerQuoted 11 lines · On Tue, 7 Jul 2026 22:15:42 +0700 Muchamad Coirul Anwar…
Add a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. The driver exposes
in_angl_rawandin_angl_scalevia the IIO sysfs interface.Features:
- ARef<I2cClient> for safe refcounted I2C client access
- Mutex-serialized status + angle read sequence
- Static channel spec (module-level const)
- No magnet validation at probe (deferred toread_rawper IIO convention)
- Error propagation via ? operator (no recovery state machine)
Quoted 8 lines
The byte order for the AS5600's big-endian registers is handled via
swap_bytes()in-driver. This is equivalent to C'si2c_smbus_read_word_swapped(). The long-term solution is regmap-rs where endianness is configured once at the transport level.Tested on BeagleBone Black (AM335x) with AS5600 on i2c-2 (
0x36).Signed-off-by Muchamad Coirul Anwar <[email protected]>
Sadly my rust remains very limited :( So you both end up at the back of my review queue and I can't provide much useful review!
Quoted 12 lines
--- drivers/iio/position/Kconfig | 14 +++ drivers/iio/position/Makefile | 1 + drivers/iio/position/as5600.rs | 181 +++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 drivers/iio/position/as5600.rsdrivers/iio/position/Kconfig +0
-0
drivers/iio/position/Kconfig line 11
Quoted 6 lines
drivers/iio/position/Kconfig +3
-0@@ -6,6 +6,20 @@ menu "Linear and angular position sensors" +config AS5600 + tristate "ams AS5600 magnetic rotary position sensor" + depends on I2C && IIO && RUST
The IIO dependence should be implicit given it is buried deep in a menu gated on that.
drivers/iio/position/Kconfig line 13
Quoted 2 lines
drivers/iio/position/Kconfig +2
-0+ help + Say Y here to build support for the ams AS5600 12-bit
This Say Y language is odd as it sort of disagrees with the M section below. Start off with what it is then finish up with any suggestions on Y vs M.
drivers/iio/position/Kconfig line 17
Quoted 4 lines
drivers/iio/position/Kconfig +4
-0+ magnetic rotary position sensor with IIO channel support + (in_angl_raw and in_angl_scale). + + This is a Rust driver that exposes the 12-bit raw angle
I think the aim is that no one configuring the kernel should even know what the language used.
drivers/iio/position/Kconfig line 18
Quoted 1 line
drivers/iio/position/Kconfig +1
-0+ and radian scale via the IIO subsystem.
I'd skip the IIO reference here given to get to this help typically someone already navigated down into the IIO menus.
Quoted 14 lines
drivers/iio/position/Kconfig +4
-0+ + 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_TESTdrivers/iio/position/as5600.rs new file +0
-0
drivers/iio/position/as5600.rs line 90
Quoted 10 lines
drivers/iio/position/as5600.rs new file +9
-0+ +static AS5600_CHANNELS: As5600Channels = As5600Channels({ + // SAFETY: `iio_chan_spec` is a repr(C) struct where all-zeroes is valid + // (integers default to 0, pointers to NULL). + let mut chan: iio_chan_spec = unsafe { core::mem::zeroed() }; + chan.type_ = iio_chan_type_IIO_ANGL; + // TODO: Use kernel::bits equivalent once bit_usize exists + chan.info_mask_separate = (1usize << iio_chan_info_enum_IIO_CHAN_INFO_RAW) + | (1usize << iio_chan_info_enum_IIO_CHAN_INFO_SCALE);
No nice BIT() equivalent? Those names end up rather repetitive with
most of it coming twice.
I don't suppose there is any way to avoid that?
Quoted 13 lines
drivers/iio/position/as5600.rs new file +13
-0+ [chan] +}); + +impl IioDriver for As5600Priv { +fn read_raw (&self, _chan: *const iio_chan_spec , mask:isize ) ->Result <IioVal > { +const INFO_RAW :isize = iio_chan_info_enum_IIO_CHAN_INFO_RAWas isize ; +const INFO_SCALE :isize = iio_chan_info_enum_IIO_CHAN_INFO_SCALEas isize ; +match mask { +// IIO_CHAN_INFO_RAW: read the 12-bit raw angle value. +INFO_RAW => { +let hw = self.io_lock.lock (); + +// Read status register to verify magnet presence before
drivers/iio/position/as5600.rs line 123
Quoted 10 lines
drivers/iio/position/as5600.rs new file +10
-0+// reading the angle. +let status = hw.client.try_read8 (AS5600_REG_STATUS as usize )?; + +// Check magnet presence (MD bit). Without a magnet the angle +// register contains stale/invalid data. +if (status &AS5600_STATUS_MD ) ==0 { +return Err (ENODATA ); + } + +// Word read at register 0x0C: SMBus read_word_data returns LE,
That seems wrong. It assumes LE data on the wire, but should return in the CPU endianness. Hence it's a swap in all cases, rather than an be16_to_cpu() which would get it backwards on a big endian platform.
Quoted 21 lines
drivers/iio/position/as5600.rs new file +21
-0+// AS5600 stores angle big-endian, so swap_bytes() is needed. +// Mutex ensures status + angle read is atomic. +// NOTE: Equivalent to C's i2c_smbus_read_word_swapped(). +// Long-term, regmap-rs with val_format_endian=Big handles +// this transparently at configuration level. +let raw = hw.client.try_read16 (AS5600_REG_RAW_ANGLE_H as usize )?; +let angle = raw.swap_bytes () &AS5600_RAW_ANGLE_MASK ; +Ok (IioVal ::Int (angleas i32 )) + } +// IIO_CHAN_INFO_SCALE: radians per LSB, 2*pi / 4096 = 0.001533981. + INFO_SCALE => { +Ok (IioVal ::IntPlusNano (0 ,1533981 )) + } + _ => Err(EINVAL), + } + } + +fn channels (&self) -> &[iio_chan_spec ] { + &AS5600_CHANNELS .0 + } +}
Quoted 2 lines · Jonathan Cameron
Sadly my rust remains very limited :( So you both end up at the back of my review queue and I can't provide much useful review!
Thanks for the review, Jonathan. Every review teaches me something regardless.
Quoted 19 lines
drivers/iio/position/Kconfig line 11
Quoted 3 lines
drivers/iio/position/Kconfig +3
-0+config AS5600 + tristate "ams AS5600 magnetic rotary position sensor" + depends on I2C && IIO && RUSTThe IIO dependence should be implicit given it is buried deep in a menu gated on that.
drivers/iio/position/Kconfig line 13
Quoted 2 lines
drivers/iio/position/Kconfig +2
-0+ help + Say Y here to build support for the ams AS5600 12-bitThis Say Y language is odd as it sort of disagrees with the M section below. Start off with what it is then finish up with any suggestions on Y vs M.
drivers/iio/position/Kconfig line 17
Quoted 4 lines
drivers/iio/position/Kconfig +4
-0+ magnetic rotary position sensor with IIO channel support + (in_angl_raw and in_angl_scale). + + This is a Rust driver that exposes the 12-bit raw angle
Quoted 7 lines
I think the aim is that no one configuring the kernel should even know what the language used.
Quoted 1 line
+ and radian scale via the IIO subsystem.
I'd skip the IIO reference here given to get to this help typically someone already navigated down into the IIO menus.
I'll drop "&& IIO" from the depends line and rewrite the help text. Device description first, Y/M hint at the end, and no mention of the implementation language.
Quoted 13 lines
drivers/iio/position/as5600.rs line 90
Quoted 9 lines
drivers/iio/position/as5600.rs new file +9
-0+ +static AS5600_CHANNELS: As5600Channels = As5600Channels({ + // SAFETY: `iio_chan_spec` is a repr(C) struct where all-zeroes is valid + // (integers default to 0, pointers to NULL). + let mut chan: iio_chan_spec = unsafe { core::mem::zeroed() }; + chan.type_ = iio_chan_type_IIO_ANGL; + // TODO: Use kernel::bits equivalent once bit_usize exists + chan.info_mask_separate = (1usize << iio_chan_info_enum_IIO_CHAN_INFO_RAW) + | (1usize << iio_chan_info_enum_IIO_CHAN_INFO_SCALE);No nice
BIT()equivalent? Those names end up rather repetitive with
most of it coming twice.
Quoted 1 line
I don't suppose there is any way to avoid that?
There's no bit_usize in kernel::bits yet. I'm considering adding it for v5 since the change is small.
Quoted 16 lines
Quoted 16 lines
drivers/iio/position/as5600.rs new file +16
-0+impl IioDriver for As5600Priv { +fn read_raw (&self, _chan: *const iio_chan_spec , mask:isize ) ->Result <IioVal > { +const INFO_RAW :isize = iio_chan_info_enum_IIO_CHAN_INFO_RAWas isize ; +const INFO_SCALE :isize = iio_chan_info_enum_IIO_CHAN_INFO_SCALEas isize ; +match mask { +// IIO_CHAN_INFO_RAW: read the 12-bit raw angle value. +INFO_RAW => { +let hw = self.io_lock.lock (); + +// Read status register to verify magnet presence before +// reading the angle. +let status = hw.client.try_read8 (AS5600_REG_STATUS as usize )?; + +// Check magnet presence (MD bit). Without a magnet the angle +// register contains stale/invalid data. +if (status &AS5600_STATUS_MD ) ==0 {
Quoted 8 lines
drivers/iio/position/as5600.rs line 123
Quoted 4 lines
drivers/iio/position/as5600.rs new file +4
-0+return Err (ENODATA ); + } + +// Word read at register 0x0C: SMBus read_word_data returns LE, That seems wrong. It assumes LE data on the wire, but should return in the CPU endianness. Hence it's a swap in all cases, rather than an
be16_to_cpu()which would get it backwards on a big endian platform.
You're right that the comment was misleading. That was my mistake. The swap is unconditional and has nothing to do with CPU endianness. I'll rewrite the comment to reflect that.
Coirul
Quoted 23 lines
Quoted 22 lines
drivers/iio/position/as5600.rs new file +21
-0+// AS5600 stores angle big-endian, so swap_bytes() is needed. +// Mutex ensures status + angle read is atomic. +// NOTE: Equivalent to C's i2c_smbus_read_word_swapped(). +// Long-term, regmap-rs with val_format_endian=Big handles +// this transparently at configuration level. +let raw = hw.client.try_read16 (AS5600_REG_RAW_ANGLE_H as usize )?; +let angle = raw.swap_bytes () &AS5600_RAW_ANGLE_MASK ; +Ok (IioVal ::Int (angleas i32 )) + } +// IIO_CHAN_INFO_SCALE: radians per LSB, 2*pi / 4096 = 0.001533981. + INFO_SCALE => { +Ok (IioVal ::IntPlusNano (0 ,1533981 )) + } + _ => Err(EINVAL), + } + } + +fn channels (&self) -> &[iio_chan_spec ] { + &AS5600_CHANNELS .0 + } +}
Hi Coirul,
Same as Jonathan on my rust capabilities (maybe now I'll have proper motivation to learn it :)).
Just one question below...
Quoted 20 lines · Muchamad Coirul Anwar
Add a Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. The driver exposes
in_angl_rawandin_angl_scalevia the IIO sysfs interface.Features:
- ARef<I2cClient> for safe refcounted I2C client access
- Mutex-serialized status + angle read sequence
- Static channel spec (module-level const)
- No magnet validation at probe (deferred toread_rawper IIO convention)
- Error propagation via ? operator (no recovery state machine)The byte order for the AS5600's big-endian registers is handled via
swap_bytes()in-driver. This is equivalent to C'si2c_smbus_read_word_swapped(). The long-term solution is regmap-rs where endianness is configured once at the transport level.Tested on BeagleBone Black (AM335x) with AS5600 on i2c-2 (
0x36).Signed-off-by Muchamad Coirul Anwar <[email protected]>---
...
drivers/iio/position/as5600.rs line 107
Quoted 4 lines
drivers/iio/position/as5600.rs new file +4
-0+impl IioDriver for As5600Priv { +fn read_raw (&self, _chan: *const iio_chan_spec , mask:isize ) ->Result <IioVal > { +const INFO_RAW :isize = iio_chan_info_enum_IIO_CHAN_INFO_RAWas isize ; +const INFO_SCALE :isize = iio_chan_info_enum_IIO_CHAN_INFO_SCALEas isize ;
Likely stupid question but do we always need the above? Some drivers might have several INFO_* bits sets and we often need to nest the match if multiple channels have the same bits. For those cases having to define all of them like this and
then doing the match seems not great to me. I guess we can directly have iio_chan_info_enum_IIO_CHAN_INFO_RAW as isize in match but not sure
if it's also that neat...
So bottom line, it would be nice if we could have something nicely readable that we could directly pass to match.
On another topic, I believe mask is present in several drivers for historic reasons but note that this parameter is not really a mask. So other name like 'info' is more appropriate.
- Nuno Sá
Quoted 7 lines · Nuno Sá
Hi Coirul,
Same as Jonathan on my rust capabilities (maybe now I'll have proper motivation to learn it :)).
Just one question below...
Hi Nuno,
Thanks for taking the time to look at this. I'm still learning too, especially on the kernel side.
Quoted 12 lines
drivers/iio/position/as5600.rs line 107
Quoted 4 lines
drivers/iio/position/as5600.rs new file +4
-0+impl IioDriver for As5600Priv { +fn read_raw (&self, _chan: *const iio_chan_spec , mask:isize ) ->Result <IioVal > { +const INFO_RAW :isize = iio_chan_info_enum_IIO_CHAN_INFO_RAWas isize ; +const INFO_SCALE :isize = iio_chan_info_enum_IIO_CHAN_INFO_SCALEas isize ;Likely stupid question but do we always need the above? Some drivers might have several INFO_* bits sets and we often need to nest the match if multiple channels have the same bits. For those cases having to define all of them like this and
then doing the match seems not great to me. I guess we can directly haveiio_chan_info_enum_IIO_CHAN_INFO_RAW as isizein match but not sure
if it's also that neat...
Quoted 2 lines
So bottom line, it would be nice if we could have something nicely readable that we could directly pass to match.
On the const definitions, yes, they are necessary in Rust. Your point about scalability is well taken though. AS5600 is simple enough that I didn't notice this, but for a driver with multiple channels and several INFO bits the const list grows quickly. Brandon Saint-John raised a related concern in v3 [1] and suggested wrapping the iio_chan_info_enum_* variants in a Rust #[repr] enum. I didn't get to it in v4 and I'm planning to address it in a future patch.
Quoted 5 lines
On another topic, I believe mask is present in several drivers for historic reasons but note that this parameter is not really a mask. So other name like 'info' is more appropriate.
- Nuno Sá
On mask vs info, you're right that mask implies a bitmask operation when what arrives is a single enum index. I'll rename it to info for v5.
Coirul
Quoted 7 lines · Muchamad Coirul Anwar
This is v4 of the Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. v3 hardened the IIO abstraction layer and introduced kernel synchronisation primitives. This revision simplifies the driver substantially based on review feedback, removes components that were over-engineered for a single-bus 12-bit sensor, and validates the result with comprehensive hardware testing.
Please Cc rust-for-linux as well for patch series that contain Rust -- thanks!
Cheers,
Miguel
Quoted 10 lines
Quoted 7 lines · Muchamad Coirul Anwar
This is v4 of the Rust driver for the ams AS5600 12-bit magnetic rotary position sensor. v3 hardened the IIO abstraction layer and introduced kernel synchronisation primitives. This revision simplifies the driver substantially based on review feedback, removes components that were over-engineered for a single-bus 12-bit sensor, and validates the result with comprehensive hardware testing.
Quoted 4 lines
Please Cc rust-for-linux as well for patch series that contain Rust -- thanks!
Cheers,
Miguel
Thanks Miguel, I missed it.
Coirul