From nobody Mon Sep 28 11:39:39 2026 Received: from mail-pj1-f53.google.com (mail-pj1-f53.google.com [209.85.216.53]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 2D1C535E1B8 for ; Sat, 22 Aug 2026 06:27:54 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.53 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380078; cv=none; b=aBp+p2ZwStPVoEgn4VXXlgO/XABMrusmBgGZNkAXfJ+yfs2B8S0vpl3ervreVffvtliP7cjHLV69nM3YdYwiI6Naxuef3dasCN2Fg4KwX/qAZCz+aJ+BBdgaX4QUYjMI0Yuc9VsdcDP24OnI9B6iyBj//62z4ttt0/f6eQJRXVI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380078; c=relaxed/simple; bh=vjRqYYnhcfNgjItxrYT6am9JhPP/wKbR3RjqpN/iHak=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=OL3C2WAk9/U3hOy26jr7/iIU+8oP/K00tc35XP5YdAbzWELZ2GtVcnW84/CnuQbmDLFEOARpCw2/W+fu3HoEC23RhOVSPW93Q98re9g2X0QWrYsuEa0j9jn22AfLBHQ6Q/O6zEHVoy5AhjvibSaj49DJfU372jcwU9o6kk2iSxM= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=cJXvpweB; arc=none smtp.client-ip=209.85.216.53 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="cJXvpweB" Received: by mail-pj1-f53.google.com with SMTP id 98e67ed59e1d1-38dc69c74b8so1846174a91.0 for ; Fri, 21 Aug 2026 23:27:54 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20251104; t=1787380074; x=1787984874; darn=vger.kernel.org; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to:content-type; bh=mTH0bdFu9fBUipWB3iUqAsha3nAp1jMUuHB4uD0PsvQ=; b=cJXvpweBVWdXNJTW0GLXY922GvBVyX9nxgT7/DEK5zVw94K4zCkFbTi/mxuKoVaETP l6O7N32wN6bdCb226RlKOV6urgHL2KdPEL1CFGWzq9vSfmcgMHYUoS78SB42AHIwmsdD UpJ6w9f1QdYm5eE27rtzOKvPBgdCe6/j+Vt2e00jl5gMCDBh8reMTXOuUbJnd1DmC1dK +PlCtWCsZzcA+cErpW8UPHJ2SuMz9bImSlET1jCGSOSIKY66Viy66GcMcxFID2UZsJhB XkSYZ6mMU8WFE4QOTVeMQdYueAquLvo1JTipe8NO7VpJs8USY64T0FW3JKWIwvvG8IXI df9Q== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1787380074; x=1787984874; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=mTH0bdFu9fBUipWB3iUqAsha3nAp1jMUuHB4uD0PsvQ=; b=h/pVx/SJTYkCZuuUIXFYORc8RyUaxoYCy1mKKS6i+42IxrUIxP+7W/540gCSEHm3yl ywfXwA1aCzUjPNqXeqU8d4YpYwl4RC1rLcZM04jaE9K3/QwZ1CpVlp/a81DYBUJ0DvZm ZZrZYepe4wEEDb4QxZNV4WGECOFC2zbh6tPTOK4O0z9dr+2qDqRNCIUjCSzdaJtE0G4H ebwfzY1f8gxH9wCX6HCYa7Pnxsasb646BeID2k7apHSF0gYamyTeCHb1AsDxo7nmY3rK pgjIpOXu+ggHmoiA4gwDJ6i7jL37h5waebApqYO1KIEjEyJ8mj43STPtI059Vi6WqEFa cWfQ== X-Forwarded-Encrypted: i=1; AHgh+Rq3gqsZiGOSxBboLZ6K9d0od43UWmcQW4iGR37hhSl0Q2lV5ffOA1UfVuR9wqonDHBrW70Zk7ST1p7+E3M=@vger.kernel.org X-Gm-Message-State: AFuF++kzlsEsFamsc4MkubLA474vHoh/FQXgBKglfq25rrjSce9AkZvj KctDbWRUUdl6AQIbFtU9xlzICs0Z/fF+TOSRnND2CCUoL3ufd5l3QR75 X-Gm-Gg: AR+sD12GfjFijCckxk+FyDZbDM3VVU9Zm2p3KaaYW1h1Oigzb/hUwUuL8T3AI8hU44r FziFVg4mjT425TuZb+sQtMmkg9F6LBijNdEpZj33aOxXpWAfEy4EvYJ7XbAMfJRMx3qOWgf/2XS xJlAXH7Ya5yiNKzK8x6oX1sHvbynofN19IsHBUwDUjK1nSGb2Ep7sT+vJRoKa/cpPmaad5a5F9s lKyPUb6YUL5tFZ7xmJFNkrt3YGxKceRBhRv3CuZtnruBKYgzkQP5PCn771lIbggIq2TonLsvpVc zmTW/fAASvEmR925wPt8XtJO65NhMv22wWISqRrPZhjdsYMtwh0GCVUCDdy1ONJlyqtTpIQAyR7 1M911LCE/7PJQdY6PUgzCWj6txrRMrxkylaFYBtSqbffdABhx+oRnCqTPS6NTyUltsxKTKDJrEb Lieb5e8rJWkGm/P5VX0RYqvW0so13ReQN6i+sKpWY+yB964m4HtqqCVvQUrgy87t0IA+6psEIBC EmcqRYNpvMwfFDbeidwHDHswVwxDH8ensUfSw== X-Received: by 2002:a17:90b:560e:b0:38e:97f0:aa4b with SMTP id 98e67ed59e1d1-395df617b34mr7689355a91.13.1787380074009; Fri, 21 Aug 2026 23:27:54 -0700 (PDT) Received: from 192.168.1.20 ([2402:8780:104c:d93:50df:47ce:56b8:7bd1]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-395c9128498sm1788519a91.2.2026.08.21.23.27.49 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 21 Aug 2026 23:27:53 -0700 (PDT) From: Muchamad Coirul Anwar To: jic23@kernel.org, lars@metafoo.de Cc: linux-iio@vger.kernel.org, linux-kernel@vger.kernel.org, linux-i2c@vger.kernel.org, rust-for-linux@vger.kernel.org, andi.shyti@kernel.org, wsa+renesas@sang-engineering.com, ojeda@kernel.org, dakr@kernel.org, igor.korotin@linux.dev, branstj@gmail.com, brucer42@gmail.com, Muchamad Coirul Anwar Subject: [RFC PATCH v5 1/3] i2c: rust: implement SMBus access via IoBackend and FallibleIoCapable Date: Sat, 22 Aug 2026 14:26:56 +0800 Message-ID: <20260822062725.60519-2-muchamadcoirulanwar@gmail.com> X-Mailer: git-send-email 2.50.0 In-Reply-To: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> References: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Implement SMBus byte and word read/write operations for I2cClient using the FallibleIoCapable trait from the generic I/O backend infrastructure. I2cClient now exposes an I2cBackend that implements FallibleIoCapable and FallibleIoCapable, replacing the previous IoCapable approach. I2C/SMBus bus transactions are inherently fallible (NACK, arbitration loss, timeout), so the infallible IoCapable is not appropriate here. FallibleIoCapable carries the errno from i2c_smbus_read_byte_data and i2c_smbus_read_word_data directly to the caller via Result. The implementation is restricted to I2cClient as I/O operations require a live device context. I2cClient::smbus_io() returns an I2cView handle for use with the generic try_read8/try_read16 methods. Two standalone methods are also provided for odd-offset word access that bypasses the alignment check in the Io trait: smbus_read_word() - CPU-native byte order (SMBus LE wire format) smbus_read_word_swapped() - byte-swapped result for big-endian devices maxsize is 256, covering the SMBus command byte range 0x00-0xFF. This is the command byte space, not the 7-bit device address which is handled by the I2C core at adapter level. Link: https://lore.kernel.org/rust-for-linux/20260131-i2c-adapter-v1-4-5a43= 6e34cd1a@gmail.com/ Link: https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-co= re.git/commit/?h=3Ddriver-core-testing&id=3D121d87b28e1d9061d3aaa156c43a627= d3cb5e620 Suggested-by: Danilo Krummrich Signed-off-by: Muchamad Coirul Anwar --- rust/kernel/bits.rs | 29 +++++ rust/kernel/i2c.rs | 302 ++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/io.rs | 66 +++++++--- 3 files changed, 377 insertions(+), 20 deletions(-) diff --git a/rust/kernel/bits.rs b/rust/kernel/bits.rs index 2daead125626..a6537a668dd6 100644 --- a/rust/kernel/bits.rs +++ b/rust/kernel/bits.rs @@ -41,6 +41,7 @@ pub const fn [](n: u32) -> $ty { impl_bit_fn!(u32); impl_bit_fn!(u16); impl_bit_fn!(u8); +impl_bit_fn!(usize); =20 macro_rules! impl_genmask_fn { ( @@ -203,3 +204,31 @@ pub const fn [](range: RangeInclusive) -> $ty { /// assert_eq!(genmask_u8(0..=3D7), u8::MAX); /// ``` ); + +impl_genmask_fn!( + usize, + /// # Examples + /// + /// ``` + /// # #![expect(clippy::reversed_empty_ranges)] + /// # use kernel::bits::genmask_checked_usize; + /// assert_eq!(genmask_checked_usize(0..=3D0), Some(0b1)); + /// assert_eq!(genmask_checked_usize(0..=3D3), Some(0b1111)); + /// assert_eq!(genmask_checked_usize(1..=3D3), Some(0b1110)); + /// + /// // `200` is out of the supported bit range on all platforms. + /// assert_eq!(genmask_checked_usize(0..=3D200), None); + /// + /// // Invalid range where the start is bigger than the end. + /// assert_eq!(genmask_checked_usize(5..=3D2), None); + /// ``` + , + /// # Examples + /// + /// ``` + /// # use kernel::bits::genmask_usize; + /// assert_eq!(genmask_usize(0..=3D0), 0b1); + /// assert_eq!(genmask_usize(0..=3D3), 0b1111); + /// assert_eq!(genmask_usize(1..=3D3), 0b1110); + /// ``` +); diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index 624b971ca8b0..f939907573a6 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -14,8 +14,15 @@ devres::Devres, driver, error::*, + io::{ + FallibleIoCapable, + IoBackend, + IoBase, + Region, // + }, of, prelude::*, + ptr::KnownSize, sync::aref::{ ARef, AlwaysRefCounted, // @@ -601,3 +608,298 @@ unsafe impl Send for Registration {} // SAFETY: `Registration` offers no interior mutability (no mutation throu= gh &self // and no mutable access is exposed) unsafe impl Sync for Registration {} + +// SAFETY: `I2cClient` wraps a kernel `struct i2c_client`. The I2C = core +// and bus locking mechanisms ensure that the underlying client structure = can +// be safely transferred between threads. +unsafe impl Send for I2cClient {} + +// SAFETY: `I2cClient` wraps a kernel `struct i2c_client`. All meth= ods +// that access the client go through kernel I2C core functions that provide +// their own synchronization. No &self method exposes interior mutability. +unsafe impl Sync for I2cClient {} + +// SAFETY: `I2cClient` is always reference-counted via the embedded +// `struct device`. `get_device`/`put_device` increment and decrement the +// device refcount atomically. A separate impl is needed for `I2cClient` +// because `AlwaysRefCounted` is not implemented generically over all +// `DeviceContext`s =E2=80=94 only the specific contexts that are safe to = refcount +// from arbitrary threads. +unsafe impl AlwaysRefCounted for I2cClient { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the= refcount is non-zero. + unsafe { bindings::get_device(self.as_ref().as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: The safety requirements guarantee that the refcount is = non-zero. + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).de= v) } + } +} + +/// I/O backend for SMBus register access via I2C. +/// +/// This backend implements only [`FallibleIoCapable`] and not [`IoCapable= `], +/// because I2C/SMBus bus transactions are inherently fallible =E2=80=94 N= ACK, +/// arbitration loss, and timeout can occur regardless of address validity. +/// The infallible [`Io::read`], [`Io::write`], and [`Io::update`] methods +/// are therefore compile-time unavailable for this backend. +pub struct I2cBackend; + +/// View type for [`I2cBackend`], carrying a reference to an I2C client and +/// a fake pointer that encodes the register offset and address-space size +/// as fat-pointer metadata. +/// +/// The pointer field is never dereferenced. After [`IoBackend::project_vi= ew`] +/// projects an offset into the pointer, `addr()` yields that offset as the +/// SMBus command byte. [`KnownSize::size()`] reads the fat-pointer metada= ta +/// length (256 for the SMBus command space). +/// +/// # Invariants +/// +/// `ptr` is a non-dereferenceable fat pointer. Its address component enco= des +/// the SMBus register offset (0..=3D255) after [`IoBackend::project_view`] +/// projection; its length metadata is 256 (the SMBus command byte address +/// space). `client` points to a valid `I2cClient` that remains live +/// for `'a`. +pub struct I2cView<'a, T: ?Sized> { + client: &'a I2cClient, + ptr: *mut T, +} + +impl Copy for I2cView<'_, T> {} + +impl Clone for I2cView<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl IoBackend for I2cBackend { + type View<'a, T: ?Sized + KnownSize> =3D 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 + KnownSiz= e>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement. + I2cView { + client: view.client, + ptr, + } + } +} + +impl FallibleIoCapable for I2cBackend { + #[inline] + fn io_try_read<'a>(view: I2cView<'a, u8>) -> Result { + // `io_view()` ensures `offset + 1 <=3D 256`, so `addr()` is at mo= st 255; + // the `as u8` cast below is therefore lossless. + let reg =3D Self::as_ptr(view).addr() as u8; + // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c= _client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_read_byte_data` is safe to call with any valid clien= t pointer + // and any u8 command byte. + let ret =3D unsafe { bindings::i2c_smbus_read_byte_data(view.clien= t.as_raw(), reg) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u8) + } + } + + #[inline] + fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result { + // `io_view()` ensures `offset + 1 <=3D 256`, so `addr()` is at mo= st 255; + // the `as u8` cast below is therefore lossless. + let reg =3D Self::as_ptr(view).addr() as u8; + // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c= _client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_write_byte_data` is safe to call with any valid clie= nt pointer + // and any u8 command byte and value. + let ret =3D unsafe { bindings::i2c_smbus_write_byte_data(view.clie= nt.as_raw(), reg, value) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(()) + } + } +} + +impl FallibleIoCapable for I2cBackend { + #[inline] + fn io_try_read<'a>(view: I2cView<'a, u16>) -> Result { + // `io_view()` ensures `offset + 2 <=3D 256`, so `addr()` is at mo= st 254; + // the `as u8` cast below is therefore lossless. + let reg =3D Self::as_ptr(view).addr() as u8; + // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c= _client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_read_word_data` is safe to call with any valid clien= t pointer + // and any u8 command byte. + let ret =3D unsafe { bindings::i2c_smbus_read_word_data(view.clien= t.as_raw(), reg) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u16) + } + } + + #[inline] + fn io_try_write<'a>(view: I2cView<'a, u16>, value: u16) -> Result { + // `io_view()` ensures `offset + 2 <=3D 256`, so `addr()` is at mo= st 254; + // the `as u8` cast below is therefore lossless. + let reg =3D Self::as_ptr(view).addr() as u8; + // SAFETY: `view.client.as_raw()` returns a valid `*mut struct i2c= _client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_write_word_data` is safe to call with any valid clie= nt pointer + // and any u8 command byte and u16 value. + let ret =3D unsafe { bindings::i2c_smbus_write_word_data(view.clie= nt.as_raw(), reg, value) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(()) + } + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for I2cView<'a, T> { + type Backend =3D I2cBackend; + type Target =3D T; + + #[inline] + fn as_view(self) -> I2cView<'a, T> { + self + } +} + +// SAFETY: `I2cView` contains `&'a I2cClient` (which is `Send` beca= use +// `I2cClient: Sync`) and `*mut T`. The raw pointer is never +// dereferenced =E2=80=94 it only encodes the SMBus register offset as its= address. +// With `T: Sync`, moving the view to another thread cannot cause data rac= es. +unsafe impl Send for I2cView<'_, T> {} + +// SAFETY: `I2cView` contains `&'a I2cClient` (which is `Sync`) and +// `*mut T`. The raw pointer is never dereferenced; sharing an `&I2cView` +// across threads is equivalent to sharing `&I2cClient` and a +// read-only address value. `T: Sync` ensures the addressed data is +// safe to access from multiple threads. +unsafe impl Sync for I2cView<'_, T> {} + +impl I2cClient { + /// Returns an I/O handle for SMBus register access on this I2C client. + /// + /// The returned handle provides fallible read/write methods for the + /// 256-byte SMBus command address space (0x00=E2=80=930xFF). This is = the SMBus + /// command byte range, NOT the 7-bit device address, which is handled + /// by the I2C core at the adapter level. + /// + /// Note: [`Io::try_read16`] and [`Io::try_write16`] on the returned h= andle + /// reject odd offsets. The underlying [`Region`] base address is 0, so + /// [`offset_valid`] checks `(0 + offset) % 2 =3D=3D 0` =E2=80=94 only= even offsets + /// pass. For word-sized access to odd-offset registers use + /// [`smbus_read_word`] or [`smbus_read_word_swapped`] instead. + /// + /// The underlying pointer in the returned [`I2cView`] is never + /// dereferenced; it encodes the register address space size as + /// fat-pointer metadata and the register offset as the pointer addres= s. + /// + /// [`smbus_read_word`]: Self::smbus_read_word + /// [`smbus_read_word_swapped`]: Self::smbus_read_word_swapped + #[inline] + pub fn smbus_io(&self) -> I2cView<'_, Region<256>> { + // INVARIANT: `client` is `self`, a valid `I2cClient`. + // + // `ptr` is a "fake pointer" =E2=80=94 it is constructed solely to= carry two + // pieces of metadata through the `IoBase` machinery: + // - address component: 0 initially; after each `project_view` c= all, + // this becomes the register offset (the SMBus command byte). + // - length metadata: 256, encoding the SMBus command address sp= ace + // size so `io_view()` can bounds-check offsets. + // + // `without_provenance_mut(0)` produces a pointer with no memory + // provenance =E2=80=94 it cannot be used to read or write memory.= This is safe + // because `I2cBackend::as_ptr()` extracts the address as a `usize` + // offset and passes it to `i2c_smbus_*` functions, never derefere= ncing + // the pointer itself. Using a provenance-free base avoids acciden= tally + // creating a pointer that appears to alias real memory. + I2cView { + client: self, + ptr: Region::<256>::ptr_from_raw_parts_mut(core::ptr::without_= provenance_mut(0), 256), + } + } + + /// Reads a 16-bit word from an SMBus register in CPU-native byte orde= r. + /// + /// Wraps `i2c_smbus_read_word_data`. The `reg` parameter is the SMBus + /// command byte (0x00=E2=80=930xFF) =E2=80=94 an instruction sent to = the device over the + /// serial bus, not a memory address. There is no alignment requiremen= t: + /// any command byte value is valid regardless of whether it is odd or= even. + /// + /// SMBus transmits the low byte first (little-endian on the wire), an= d this + /// method returns the value in CPU-native byte order without further + /// conversion. Use [`Self::smbus_read_word_swapped`] for devices that= store + /// multi-byte registers in big-endian (MSB-first) format. + /// + /// Returns `Err` if the bus transaction fails (e.g. NACK, arbitration= loss, + /// or timeout). + #[inline] + pub fn smbus_read_word(&self, reg: u8) -> Result { + // 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 =3D unsafe { bindings::i2c_smbus_read_word_data(self.as_ra= w(), reg) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok(ret as u16) + } + } + + /// Reads a 16-bit word from an SMBus register with bytes unconditiona= lly + /// swapped. + /// + /// Wraps `i2c_smbus_read_word_data` and applies [`u16::swap_bytes`] t= o the + /// result. Use this for devices that store multi-byte registers in + /// big-endian (MSB-first) format, which is common among I2C sensors w= hose + /// datasheets do not reference the SMBus specification. + /// + /// The swap is **unconditional** =E2=80=94 it is not equivalent to `b= e16_to_cpu`. + /// On a big-endian CPU, `be16_to_cpu` would be a no-op, but this meth= od + /// still swaps. The reason: SMBus always transmits the low byte first= , so + /// the driver always receives data in little-endian wire order regard= less + /// of CPU endianness. The swap corrects for the device's wire-level b= yte + /// order, not the CPU's native order. + /// + /// The `reg` parameter is the SMBus command byte (0x00=E2=80=930xFF).= There is no + /// alignment requirement; any command byte value is valid. + /// + /// Returns `Err` if the bus transaction fails (e.g. NACK, arbitration= loss, + /// or timeout). + /// + /// # Example + /// + /// ```ignore + /// // AS5600 stores the 12-bit raw angle big-endian at register 0x0C. + /// let raw =3D client.smbus_read_word_swapped(0x0C)?; + /// let angle =3D raw & 0x0FFF; + /// ``` + #[inline] + pub fn smbus_read_word_swapped(&self, reg: u8) -> Result { + // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client` + // pointer as guaranteed by the type invariant of `I2cClient`. + let ret =3D unsafe { bindings::i2c_smbus_read_word_data(self.as_ra= w(), reg) }; + if ret < 0 { + Err(Error::from_errno(ret)) + } else { + Ok((ret as u16).swap_bytes()) + } + } +} diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs index 95f46bb75f9e..516895ca2082 100644 --- a/rust/kernel/io.rs +++ b/rust/kernel/io.rs @@ -276,6 +276,36 @@ pub trait IoCapable: IoBackend { fn io_write<'a>(view: Self::View<'a, T>, value: T); } =20 +/// Fallible counterpart of [`IoCapable`] for I/O backends where operation= s 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 implement= ing [`IoCapable`]; the +/// infallible [`Io::read`], [`Io::write`], and [`Io::update`] methods wil= l then be unavailable, +/// enforcing that callers use the `try_*` variants instead. +pub trait FallibleIoCapable: 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; + + /// 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, T> FallibleIoCapable for B { + #[inline(always)] + fn io_try_read<'a>(view: Self::View<'a, T>) -> Result { + Ok(Self::io_read(view)) + } + + #[inline(always)] + fn io_try_write<'a>(view: Self::View<'a, T>, value: T) -> Result { + Self::io_write(view, value); + Ok(()) + } +} + /// Trait indicating that an I/O backend supports memory copy operations. pub trait IoCopyable: IoBackend { /// Copy contents of `view` to `buffer`. @@ -645,7 +675,7 @@ fn copy_to_slice(self, data: &mut [u8]) fn try_read8(self, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_read(offset) } @@ -655,7 +685,7 @@ fn try_read8(self, offset: usize) -> Result fn try_read16(self, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_read(offset) } @@ -665,7 +695,7 @@ fn try_read16(self, offset: usize) -> Result fn try_read32(self, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_read(offset) } @@ -675,7 +705,7 @@ fn try_read32(self, offset: usize) -> Result fn try_read64(self, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_read(offset) } @@ -685,7 +715,7 @@ fn try_read64(self, offset: usize) -> Result fn try_write8(self, value: u8, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_write(offset, value) } @@ -695,7 +725,7 @@ fn try_write8(self, value: u8, offset: usize) -> Result fn try_write16(self, value: u16, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_write(offset, value) } @@ -705,7 +735,7 @@ fn try_write16(self, value: u16, offset: usize) -> Resu= lt fn try_write32(self, value: u32, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_write(offset, value) } @@ -715,7 +745,7 @@ fn try_write32(self, value: u32, offset: usize) -> Resu= lt fn try_write64(self, value: u64, offset: usize) -> Result where usize: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { self.try_write(offset, value) } @@ -827,10 +857,10 @@ fn write64(self, value: u64, offset: usize) fn try_read(self, location: L) -> Result where L: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { let view =3D io_view::(self, location.offset())?; - Ok(Self::Backend::io_read(view).into()) + Ok(Self::Backend::io_try_read(view)?.into()) } =20 /// Generic fallible write with runtime bounds check. @@ -860,12 +890,11 @@ fn try_read(self, location: L) -> Result fn try_write(self, location: L, value: T) -> Result where L: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { let view =3D io_view::(self, location.offset())?; let io_value =3D value.into(); - Self::Backend::io_write(view, io_value); - Ok(()) + Self::Backend::io_try_write(view, io_value) } =20 /// Generic fallible write of a fully-located register value. @@ -905,7 +934,7 @@ fn try_write_reg(self, value: V) -> Result where L: IoLoc, V: LocatedRegister, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, { let (location, value) =3D value.into_io_op(); =20 @@ -938,16 +967,13 @@ fn try_write_reg(self, value: V) -> Result fn try_update(self, location: L, f: F) -> Result where L: IoLoc, - Self::Backend: IoCapable, + Self::Backend: FallibleIoCapable, F: FnOnce(T) -> T, { let view =3D io_view::(self, location.offset())?; - - let value: T =3D Self::Backend::io_read(view).into(); + let value: T =3D Self::Backend::io_try_read(view)?.into(); let io_value =3D f(value).into(); - Self::Backend::io_write(view, io_value); - - Ok(()) + Self::Backend::io_try_write(view, io_value) } =20 /// Generic infallible read with compile-time bounds check. --=20 2.50.0 From nobody Mon Sep 28 11:39:39 2026 Received: from mail-pj1-f54.google.com (mail-pj1-f54.google.com [209.85.216.54]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 84D3C361640 for ; Sat, 22 Aug 2026 06:28:07 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.54 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380089; cv=none; b=BRKnWW8rRIyo4Twmri7w6jitvXWGaFke30vnRO2i8XrsBTV7pFKCm9SV1ov1MU/JcRvoizPUF7Nz9fHCCyrnj4/FsbdR9EEWa7WblKRTbdwI5AoPirDM8bhB67Wlk2tChLkLqUIy63LtySCdocMvfqaa7fa+BVVm96tu5mZkC8o= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380089; c=relaxed/simple; bh=LeFmW1bluMMHtZuqzUzuWC1/AbiAuVOUNqu80b8ZZpw=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=oBZjklxQke3rcizhqIomjhC3DkUBlqLFDaCcDSGc1NoL9DJtZlQMcysnHc51wKXq2I92llQ3wJW0NQq6k2gjU13edQ7jwrov9dqrLZRO1sBTMulPTr8edoK3BAR7eydh2nRd8+O8aderFc3+Ru9R+il1sNVBYMXVRCgLnt7e2so= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=otqZrXMs; arc=none smtp.client-ip=209.85.216.54 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="otqZrXMs" Received: by mail-pj1-f54.google.com with SMTP id 98e67ed59e1d1-38f620399a0so1467377a91.2 for ; Fri, 21 Aug 2026 23:28:07 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20251104; t=1787380087; x=1787984887; darn=vger.kernel.org; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to:content-type; bh=8lBFakgLXC0ohAGK9NN6FmmM+xAFSCRw3E7XUA+x/pY=; b=otqZrXMsKcb5WbMMLN52REd3J05PMB8/b+vjle7hUcZceSVasLj/u/R2dgPJxdYBUY r4+6IeYiGwkwqS0WOCtixTQVYaj8WV1KPLQIgnK7MZCXwWwCE+as602rIZQgW7X06Baq 7K8kZzl5MS13TcuDeH287WxUY6RtJx8UnucoMIjPDtkLP8HYdp3iTa1eTQhIOZI7m111 DdhCMlMMZmSsnG4Xe9kKrAfTWwx9HycaqlZGB40n6XyqsEc0pL1++77qEFTTCm/8ZMEw XTYtIR2Z34C20f7/m8xzznBaSlvABpwTOaytUcR9hvCVIkJssjYB7zkhIoYG6c/OnsRq Xgng== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1787380087; x=1787984887; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=8lBFakgLXC0ohAGK9NN6FmmM+xAFSCRw3E7XUA+x/pY=; b=abZGIrQ5jrSFqqZM8BeX0pDT9m6poKN132D1vzB+OZoYKLNoUzUoHwIOWclVvrEOBH nyaDpz9ptDt9t+Z5apQTPdSi1Ok2kUG1Qbb0jTm5hMU/vE39FAsJa3GRCXK1CrhxB7TU /DeteaG4N7uePclxfFwvMW9pmrQscYUWPxH1B5YMg/1t8SA+jUrGDyM2tzFTITGVtUz/ D9NJXJ3DGZq4I29QDBYsbzZ6NqkxLzuRLs7B717uT2AIjcUKsmYYIv9nYehbYC3l20YI EIILKgemCMUD2B3PTA0xYnLnIiUZO9/WBK7lMsm+CnQ943y5czc/eyMjsQP7RNZw5MTN dHNw== X-Forwarded-Encrypted: i=1; AHgh+RotoawVawQrQsuJ4/njPnGyvoY8MITtUj7ko3Lu62nwSGsm7SmaifoWD4CllUoRpobci8M4i6Yoyiclzv4=@vger.kernel.org X-Gm-Message-State: AFuF++nTGvuls0SfeALqGAAvNHv06UCMxsnRxDUdy9PV6Gkw2XQJlpag dmSaGrxRtl6lZHBmIHRH3gEgmmx7T/OIzmYVpFEZvPFIuZ0ToQkBS12h X-Gm-Gg: AR+sD134AbsDZmQdm2D+cSZfdBzu0XJH3QaFaoCl69WWM32hKwIJYbpxF2ZaRARNsfc T1Li8Iq/dgEc3Sn3YTW+LHYqeBmuEyZXSBdDKR7Q4klZA5ha1jbNtS0zfiQsYTMENSR4V3MfHst t1I8W6b8pZPqRj6OUhpuc2MD5HAQB4sGpmmVYymYvbbbaIcVtxjhhRsfM9w4R+O+dMlYx0IyjVj ww3/V7xbWXrRcq6Y2Moyu9EksvkfS4oF9/7bcsz1903gQnv7jpvnOtVppMuYJXsEY5f1lQXZA1Y iA2nG3mBCT3xjCCWP5qQt5I9w5Lirgd7UIF50/Nx43CF5b7j8fbOayjxpLVKMcBhz1emDgQQEQO c4eqaw/uovyR/RLoPKdwW1dMtvdBSt/cuMtERTxzAGZ1cTZZZ+mlOX1VOPivn2WSr43hhhGeQHk bCQz8/upoXEh94VXAjfywV/jt+S8A6wLm7p6d5TgyfWfj5FXVznDNCG/eKYLC1IQDO9wTHPjIW+ 477muvz1fA8TC1DO9PG56fv28o= X-Received: by 2002:a17:90b:55cc:b0:37c:6910:5758 with SMTP id 98e67ed59e1d1-395c334042emr23712958a91.1.1787380086618; Fri, 21 Aug 2026 23:28:06 -0700 (PDT) Received: from 192.168.1.20 ([2402:8780:104c:d93:50df:47ce:56b8:7bd1]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-395c9128498sm1788519a91.2.2026.08.21.23.28.02 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 21 Aug 2026 23:28:06 -0700 (PDT) From: Muchamad Coirul Anwar To: jic23@kernel.org, lars@metafoo.de Cc: linux-iio@vger.kernel.org, linux-kernel@vger.kernel.org, linux-i2c@vger.kernel.org, rust-for-linux@vger.kernel.org, andi.shyti@kernel.org, wsa+renesas@sang-engineering.com, ojeda@kernel.org, dakr@kernel.org, igor.korotin@linux.dev, branstj@gmail.com, brucer42@gmail.com, Muchamad Coirul Anwar Subject: [RFC PATCH v5 2/3] rust: add minimal IIO subsystem abstractions Date: Sat, 22 Aug 2026 14:26:57 +0800 Message-ID: <20260822062725.60519-3-muchamadcoirulanwar@gmail.com> X-Mailer: git-send-email 2.50.0 In-Reply-To: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> References: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add safe Rust wrappers for the Linux IIO (Industrial I/O) subsystem: - IioChanInfo enum wrapping iio_chan_info_enum, with TryFrom for type-safe dispatch in read_raw. The compiler enforces match exhaustiveness, replacing the previous raw isize approach. - IioVal enum with NonZeroI32 for division-by-zero prevention on IIO_VAL_FRACTIONAL. - IioDriver trait with read_raw callback (requires Send + Sync). - Device with typestate (Unregistered -> Registered) to prevent double-registration at compile time. - PinnedDrop for guaranteed cleanup sequence: iio_device_unregister -> drop_in_place(T) -> iio_device_free iio_device_unregister() calls cdev_device_del() which drains the kernfs workqueue before returning. All in-flight read_raw callbacks (which go through kernfs sysfs reads) complete before drop_in_place proceeds. This covers the sysfs read path used by this driver. - 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). Signed-off-by: Muchamad Coirul Anwar --- rust/bindings/bindings_helper.h | 2 + rust/kernel/error.rs | 1 + rust/kernel/iio.rs | 384 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 389 insertions(+) create mode 100644 rust/kernel/iio.rs diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 1124785e210b..f311959bab18 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -62,6 +62,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index a56ba6309594..5dc917d92151 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -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."); } =20 /// Generic integer kernel error. diff --git a/rust/kernel/iio.rs b/rust/kernel/iio.rs new file mode 100644 index 000000000000..f1638160fed1 --- /dev/null +++ b/rust/kernel/iio.rs @@ -0,0 +1,384 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (C) 2026 Muchamad Coirul Anwar +//! IIO subsystem abstractions. +//! +//! Minimal safe Rust wrappers for the Linux IIO (Industrial I/O) subsyste= m. +//! Provides [`Device`] for allocating and registering an IIO device, and = the +//! [`IioDriver`] trait for implementing `read_raw` callbacks in safe Rust. + +use crate::{ + bindings::{ + __iio_device_register, + iio_chan_spec, + iio_dev, + iio_device_alloc, + iio_device_free, + iio_device_unregister, + iio_info, // + }, + device, + error::{ + code::*, + to_result, + Result, // + }, + prelude::*, + ThisModule, // +}; + +use core::{ + ffi::c_int, + marker::PhantomData, + mem::{ + forget, + size_of, + zeroed, // + }, + num::NonZeroI32, + pin::Pin, + ptr::drop_in_place, // +}; + +use pin_init::{ + pin_data, + pinned_drop, // +}; + +/// IIO value type: single integer (`IIO_VAL_INT`). +pub const IIO_VAL_INT: c_int =3D crate::bindings::IIO_VAL_INT as c_int; +/// IIO value type: integer plus micro part (`IIO_VAL_INT_PLUS_MICRO`). +pub const IIO_VAL_INT_PLUS_MICRO: c_int =3D crate::bindings::IIO_VAL_INT_P= LUS_MICRO as c_int; +/// IIO value type: integer plus nano part (`IIO_VAL_INT_PLUS_NANO`). +pub const IIO_VAL_INT_PLUS_NANO: c_int =3D crate::bindings::IIO_VAL_INT_PL= US_NANO as c_int; +/// IIO value type: fractional (`IIO_VAL_FRACTIONAL`). +pub const IIO_VAL_FRACTIONAL: c_int =3D crate::bindings::IIO_VAL_FRACTIONA= L as c_int; + +/// Generates a Rust enum wrapper for C `enum iio_chan_info_enum`. +/// +/// This macro creates a type-safe enum with automatic `TryFrom` +/// conversion. Drivers match directly on `IioChanInfo` variants in +/// `read_raw`, and the compiler enforces match exhaustiveness. +/// Additional variants can be added as drivers require them. +macro_rules! build_iio_enum { + ( + $( + $(#[$meta:meta])* + $rust_name:ident =3D $c_const:ident + ),* $(,)? + ) =3D> { + /// Channel info attribute selector for [`IioDriver::read_raw`]. + /// + /// Wraps C `enum iio_chan_info_enum` values. The IIO core passes = this + /// to `read_raw` to indicate which attribute userspace is reading + /// (e.g., raw value, scale factor, offset). + /// + /// Currently covers the subset needed by in-tree Rust drivers. + /// Additional variants from `include/linux/iio/types.h` can be + /// added as needed. + #[repr(u32)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum IioChanInfo { + $( + $(#[$meta])* + $rust_name =3D bindings::$c_const, + )* + } + impl TryFrom for IioChanInfo { + type Error =3D Error; + fn try_from(value: u32) -> Result { + match value { + $( bindings::$c_const =3D> Ok(IioChanInfo::$rust_name)= , )* + _ =3D> Err(EINVAL), + } + } + } + }; +} + +build_iio_enum! { + /// Raw unprocessed value from the channel (`IIO_CHAN_INFO_RAW`). + /// + /// For sensors, this is typically the ADC reading or register value + /// before any scaling or offset correction. + Raw =3D iio_chan_info_enum_IIO_CHAN_INFO_RAW, + /// Scale factor to convert raw values to SI units (`IIO_CHAN_INFO_SCA= LE`). + /// + /// The processed value is `raw * scale`. The unit depends on the chan= nel + /// type (e.g. V for voltage, m/s=C2=B2 for acceleration, rad for angl= e). + Scale =3D iio_chan_info_enum_IIO_CHAN_INFO_SCALE, +} + +/// Represents the return value of a `read_raw` operation. +/// +/// Each variant corresponds to an `IIO_VAL_*` constant and tells the +/// IIO core how to format `val` and `val2` for userspace. +pub enum IioVal { + /// A single integer value. + Int(i32), + /// A fractional value represented as `val / val2`. + /// The denominator is `NonZeroI32` to prevent division-by-zero in + /// `iio_format_value()`. + Fractional(i32, NonZeroI32), + /// An integer plus a micro (1e-6) fractional part: `val.val2`. + IntPlusMicro(i32, i32), + /// An integer plus a nano (1e-9) fractional part: `val.val2`. + IntPlusNano(i32, i32), +} + +/// Trait to be implemented by IIO driver private data. +/// +/// Implementors supply the `read_raw` callback invoked by the IIO core +/// when userspace reads a channel attribute (e.g. `in_angl_raw`). +/// +/// The `Send + Sync` bounds ensure the compiler rejects driver types with +/// thread-unsafe interior mutability (e.g. `Cell`), since the IIO core may +/// invoke `read_raw` concurrently from multiple sysfs readers. +pub trait IioDriver: Send + Sync { + /// Called by the IIO core when userspace reads a channel attribute. + /// + /// `chan` is the channel being read; `info` selects the attribute + /// (e.g. `IIO_CHAN_INFO_RAW`, `IIO_CHAN_INFO_SCALE`). + fn read_raw(&self, chan: *const iio_chan_spec, info: IioChanInfo) -> R= esult; + + /// Returns the channel specifications for this driver. + /// + /// The default implementation returns an empty slice. + fn channels(&self) -> &'static [iio_chan_spec] { + &[] + } +} + +/// C-compatible trampoline for the `iio_info.read_raw` callback. +/// +/// # Safety +/// +/// This function is only called by the IIO core via the `read_raw` functi= on +/// pointer in `iio_info`. The IIO core guarantees: +/// - `indio_dev` is a valid `iio_dev` allocated by `iio_device_alloc`. +/// - `chan` points to a valid channel spec from the device's channel arra= y. +/// - `val` is a valid non-null pointer to a writable `int`. +/// - `val2` is a valid non-null pointer to a writable `int`. The IIO core +/// always passes stack-allocated storage for both, regardless of whether +/// the driver uses `val2` (e.g. `IIO_VAL_INT` only writes `val`; `val2` +/// is provided but left unread by the caller for that return type). +unsafe extern "C" fn read_raw_callback( + indio_dev: *mut iio_dev, + chan: *const iio_chan_spec, + val: *mut c_int, + val2: *mut c_int, + info: isize, +) -> c_int { + // SAFETY: `indio_dev` is valid and was allocated with space for `T` i= n its + // private data area. The `priv_` field was initialized in `Device::bu= ild_device()`. + let priv_ptr =3D unsafe { (*indio_dev).priv_ as *mut T }; + // SAFETY: `priv_ptr` points to a valid, initialized instance of `T` t= hat + // lives as long as the `iio_dev` allocation. + let driver =3D unsafe { &*priv_ptr }; + + let info_enum =3D match IioChanInfo::try_from(info as u32) { + Ok(valid) =3D> valid, + Err(e) =3D> return e.to_errno(), + }; + + match driver.read_raw(chan, info_enum) { + Ok(IioVal::Int(v)) =3D> { + // SAFETY: `val` is valid per the function's Safety contract a= bove. + // `val2` is not written; `IIO_VAL_INT` signals to the IIO core + // that only `val` carries meaningful data. + unsafe { + *val =3D v; + } + IIO_VAL_INT + } + Ok(IioVal::Fractional(v, v2)) =3D> { + // SAFETY: both `val` and `val2` are valid per the Safety cont= ract. + unsafe { + *val =3D v; + *val2 =3D v2.get(); + } + IIO_VAL_FRACTIONAL + } + Ok(IioVal::IntPlusMicro(v, v2)) =3D> { + // SAFETY: both `val` and `val2` are valid per the Safety cont= ract. + unsafe { + *val =3D v; + *val2 =3D v2; + } + IIO_VAL_INT_PLUS_MICRO + } + Ok(IioVal::IntPlusNano(v, v2)) =3D> { + // SAFETY: both `val` and `val2` are valid per the Safety cont= ract. + unsafe { + *val =3D v; + *val2 =3D v2; + } + IIO_VAL_INT_PLUS_NANO + } + Err(e) =3D> e.to_errno(), + } +} + +// Device: IIO device wrapper with typestate. + +/// Marker type for an unregistered IIO device. +pub struct Unregistered; +/// Marker type for a registered IIO device. +pub struct Registered; + +/// A wrapped IIO device managing its C `struct iio_dev` lifetime. +/// +/// Uses `iio_device_alloc` for allocation (not devres) and manual cleanup +/// via `Drop`: `iio_device_unregister` -> `drop_in_place` for `T` -> +/// `iio_device_free`. +/// +/// # Invariants +/// +/// - `indio_dev` is a valid pointer to an `iio_dev` allocated by `iio_dev= ice_alloc`. +/// - If `registered` is true, the device was successfully registered via +/// `__iio_device_register`. +#[pin_data(PinnedDrop)] +pub struct Device { + indio_dev: *mut iio_dev, + registered: bool, + _p: PhantomData<(T, State)>, +} + +// SAFETY: `Device` only contains a raw pointer to a kernel-managed `iio_d= ev`. +// The IIO core serializes access to the device, and `T` is required to be= `Send`. +unsafe impl Send for Device {} +// SAFETY: All `&self` access to the `iio_dev` is read-only or goes throug= h the +// IIO core which provides its own synchronization. `T` is required to be = `Sync`. +unsafe impl Sync for Device {} + +#[pinned_drop] +impl PinnedDrop for Device { + fn drop(self: Pin<&mut Self>) { + if self.registered { + // SAFETY: `__iio_device_register` succeeded. + // + // iio_device_unregister() removes sysfs entries via kernfs, w= hich + // calls kernfs_drain() to wait for all in-flight sysfs attrib= ute + // reads to complete before returning. Drivers that only use s= ysfs + // access paths (INDIO_DIRECT_MODE without buffer/trigger) are + // guaranteed that no read_raw callback is in flight after thi= s. + // + // For drivers with buffer support, additional synchronization + // analysis is required for character device paths, which are = NOT + // covered by kernfs_drain(). + unsafe { iio_device_unregister(self.indio_dev) }; + } + + // SAFETY: `priv_` was fully initialized in `build_device` via + // `init.__pinned_init(priv_ptr)`. `drop_in_place` runs `T`'s dest= ructor + // (including any pinned fields like Mutex). After that, `iio_devi= ce_free` + // calls `put_device` which decrements the kref. The underlying `i= io_dev` + // memory is only freed when kref reaches 0. + unsafe { + let priv_ptr =3D (*self.indio_dev).priv_ as *mut T; + drop_in_place(priv_ptr); + iio_device_free(self.indio_dev); + } + } +} + +impl Device { + // SAFETY: + // - `read_raw_callback::` is a valid function pointer whose signat= ure + // matches the IIO core's `read_raw` contract. + // - All remaining fields are pointers or function pointers; zeroed va= lues + // are NULL, and the IIO core checks for NULL before invoking any op= tional + // callback or dereferencing any optional attribute group. + const VTABLE: iio_info =3D iio_info { + read_raw: Some(read_raw_callback::), + ..unsafe { zeroed() } + }; + + /// Allocates a new IIO device with the given driver data. + /// + /// Uses `iio_device_alloc` (not `devm_*`) so that the Rust `Drop` + /// implementation has full control over the cleanup sequence. + /// The device is not yet registered; call [`register`](Self::register) + /// to make it visible to userspace. + pub fn build_device( + dev: &device::Device, + name: &'static CStr, + modes: u32, + init: impl PinInit, + ) -> Result + where + Error: From, + { + let priv_size =3D i32::try_from(size_of::()).map_err(|_| EINVAL= )?; + + // SAFETY: `dev.as_raw()` returns a valid `struct device` pointer. + // `iio_device_alloc` allocates an `iio_dev` with `sizeof(T)` byte= s of + // private data. Returns NULL on failure. + let indio_dev =3D unsafe { iio_device_alloc(dev.as_raw(), priv_siz= e) }; + if indio_dev.is_null() { + return Err(ENOMEM); + } + + // SAFETY: `indio_dev` is valid and freshly allocated. `priv_` poi= nts to + // zeroed memory (kzalloc'd by iio_device_alloc). `PinInit::__pinn= ed_init` + // overwrites it in place without reading previous contents. + let priv_ptr =3D unsafe { (*indio_dev).priv_ as *mut T }; + let init_result =3D unsafe { init.__pinned_init(priv_ptr) }; + if let Err(e) =3D init_result { + // SAFETY: `pin_init` guarantees partial-init rollback interna= lly. + // `priv_` memory was not fully initialized, so we only free t= he + // container without running `T`'s destructor. + unsafe { iio_device_free(indio_dev) }; + return Err(Error::from(e)); + } + + // SAFETY: `priv_ptr` is now fully initialized. We set up the IIO + // device fields: + // - `name` is a `'static` C string that outlives the device. + // - `VTABLE` is a `'static` const and outlives the device. + // - `channels()` is required to return a `'static` slice (trait + // contract). The pointer stored in `indio_dev.channels` therefo= re + // remains valid for the entire lifetime of the `iio_dev` alloca= tion + // (until `iio_device_free`), because static data outlives any + // allocation. + // - `modes` is passed by the caller and stored as-is. + unsafe { + (*indio_dev).name =3D name.as_char_ptr(); + (*indio_dev).info =3D &Self::VTABLE; + + let chans =3D (*priv_ptr).channels(); + (*indio_dev).channels =3D chans.as_ptr(); + (*indio_dev).num_channels =3D chans.len() as _; + (*indio_dev).modes =3D modes as i32; + } + + Ok(Self { + indio_dev, + registered: false, + _p: PhantomData, + }) + } + + /// Registers the IIO device, making it visible to userspace via sysfs. + /// + /// On success, channel attributes like `in_angl_raw` become readable. + /// On failure the device stays unregistered and will be freed when + /// this [`Device`] is dropped. + #[inline] + pub fn register(self, module: &'static ThisModule) -> Result> { + // SAFETY: `self.indio_dev` is a valid, fully initialized `iio_dev= `. + // `module.as_ptr()` provides the module owner for proper refcount= ing. + let ret =3D unsafe { __iio_device_register(self.indio_dev, module.= as_ptr()) }; + to_result(ret)?; + + let registered_dev =3D Device { + indio_dev: self.indio_dev, + registered: true, + _p: PhantomData, + }; + + // Prevent `self`'s Drop from running. Ownership of `indio_dev` + // has been transferred to `registered_dev`. + forget(self); + Ok(registered_dev) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 68f4d9a3425d..726a23e2d579 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -81,6 +81,8 @@ #[cfg(CONFIG_I2C =3D "y")] pub mod i2c; pub mod id_pool; +#[cfg(CONFIG_IIO)] +pub mod iio; #[doc(hidden)] pub mod impl_flags; pub mod init; --=20 2.50.0 From nobody Mon Sep 28 11:39:39 2026 Received: from mail-pj1-f43.google.com (mail-pj1-f43.google.com [209.85.216.43]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id A9786361640 for ; Sat, 22 Aug 2026 06:28:27 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.216.43 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380109; cv=none; b=oHxYSpW5cwdp4EWQLCUoEIxoq+Od/XbATwLpNSHyB0AU2Fpp151USt7N4Mty6NZh4WsZYKDmALucT3TL+WXsj3mZCKFuoiC/6Aj7EOpTm2UIV4g50GCHI0GEmkXc/dP0UUCYM1Z2DTsx0auLBP6SBA6kby3wogHftY3Rw9d8i8Q= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1787380109; c=relaxed/simple; bh=uAwhE2kHU9mqidDO2nmljYr7WfPvu+fcYAQliNjCrVI=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=oznwAalfki6XN/gAarqO62dL2jaz+d5INdRgxU2bM8q07ALpr0bQxB9hgSwPHLWU3Nvj0e9gdbeb9gupfrkEU8gy9KDQ1FTttsqNyvlYbmm2hiB+USzMeAUfF4E4TD7tynD6dyDSaXHymwFfNmUqbpJ83J+2ZqqYKJ1eG4WJ7Bg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b=LLu2HBcf; arc=none smtp.client-ip=209.85.216.43 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.b="LLu2HBcf" Received: by mail-pj1-f43.google.com with SMTP id 98e67ed59e1d1-38ec1402b05so1297186a91.2 for ; Fri, 21 Aug 2026 23:28:27 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20251104; t=1787380107; x=1787984907; darn=vger.kernel.org; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to:content-type; bh=Tag2M6Utu+miagcXfcnjHgNWD2M3eOPe/bDAJrnpofs=; b=LLu2HBcfTONpKF0U/j/TXldTT3zAAQ9YNHx7z3SI9+fiYQNIdREQW58kQ+HjQ+cTO8 RDshN2FAwnmTagyxN+6jF0HKt6rwgKfxd3QokkCMi6l1k+c+GGomUdoOXtEXIIhZ4okL A1VlbtquYPKwDHRppkvPTDZVzFLvAuDlML8n0XmA1XtdEfeAGVixjHgFwvmjYeUdTV8n KBB7rBwmM/eoFbvwh0Hn1B/SNVNbrcvDioDnuQtgxnN/by6rgc787BL6ARh5wTL5elRI BVH9i1tYpscLZdEGq3EE1c9ubBfiTpYMx/xD0J6psJXkJrpCFLG4MZhCZEMD95RXU2bN w71g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1787380107; x=1787984907; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=Tag2M6Utu+miagcXfcnjHgNWD2M3eOPe/bDAJrnpofs=; b=eosmD7WRaMNSrDJmKWA4a8PAruLTMQReZao432CO0u3BBTvz+QUHmvT9QILe6Atm89 kc5C4oTGnp0/bV0IeQR6iaHxOUYrkOZmH9hLHaxmyihERb/AP8z0tUv/G43NXfmb8lPr wue6veXQ0JlFURZvksYYf3zLLbdQOQpYQbevXPNYbnt03bQeKgng6sS2YovTO93DDIxG OQy8bXCLNK6PrFK69ArskShCCVAyI0SaHM++45UmwMi9CWQ71l9g0B3oiUyrlhrHWLIN 4NLE6UxnSQH4R7WsoyGVMYh7+WU0tOYcrZF0si1jLbNwe0xaM2f0awE1MlLVkOvMoeoS xOMw== X-Forwarded-Encrypted: i=1; AHgh+RrR/QZ8PVmHq81qrfyrvJ/EvluzYh261qVeFBqsl5ipGyk0FYkPylLUAWhS5Z9QUAF6qwaRFOXrgxrMBGY=@vger.kernel.org X-Gm-Message-State: AFuF++mBa0QpW98ZKg/1VhlsphOwdXIaLgace3vvhwp+UhphqjtqSfd6 C1fBvS8LHzenjUPVNjaGPlkSP/QN8CuZ77F9sNQkcqbNc+2vQGvx1afV X-Gm-Gg: AR+sD11i513j6YcwBvPUoHHCTB+FIEWxj/bSCLuyQy4CCKDTQKXxzCxHnoc4JjphHgQ vU9J6Ff++Q604wbO+jmJofI/WFS/IcWhI2UcHf3fYxtgkyUPp/nFDVr8MumeXdhc8zvkai0ljtM WxruQiyzjlfJ6vnewPRtgA1Bv5T0bczNS2R4RJp4aiQZF0NfmNnyCBQz4vPjIY2D9yxRzSwKTtU b3GADRGDOwvqqFU1cctub58ZskCiP7rkNGcaix81/tWY3PGAyEHahZcH1D/zN1k9oEVg+EMC2x8 9Q6dAEPzn4uwAKBkXWzGjKxY2h5Qzm+0TEXABE2WhjHfrciT19PLx9JrPN4K6spYYaBurCQnHxz cGuf84K+BqX1vzyEddC67oY+v5flnWF1/VF8uySzo5MDl1ApM3xLwOpPNsk+QmunMP1/S/bpp/q KgdBZm9o2f6lnzFmTDOuhUG7nhw8oSySD0LZeo4O7mvi+KSObB2nGyX3818cXuLk9AhPorUOSTx 9tu6i0+7qmLHvUU5MZZaLMTJPhQTDDNF9174A== X-Received: by 2002:a17:90b:528f:b0:380:f85c:94b4 with SMTP id 98e67ed59e1d1-395c35636acmr21996808a91.7.1787380106743; Fri, 21 Aug 2026 23:28:26 -0700 (PDT) Received: from 192.168.1.20 ([2402:8780:104c:d93:50df:47ce:56b8:7bd1]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-395c9128498sm1788519a91.2.2026.08.21.23.28.22 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Fri, 21 Aug 2026 23:28:26 -0700 (PDT) From: Muchamad Coirul Anwar To: jic23@kernel.org, lars@metafoo.de Cc: linux-iio@vger.kernel.org, linux-kernel@vger.kernel.org, linux-i2c@vger.kernel.org, rust-for-linux@vger.kernel.org, andi.shyti@kernel.org, wsa+renesas@sang-engineering.com, ojeda@kernel.org, dakr@kernel.org, igor.korotin@linux.dev, branstj@gmail.com, brucer42@gmail.com, Muchamad Coirul Anwar Subject: [RFC PATCH v5 3/3] iio: position: add Rust driver for ams AS5600 Date: Sat, 22 Aug 2026 14:26:58 +0800 Message-ID: <20260822062725.60519-4-muchamadcoirulanwar@gmail.com> X-Mailer: git-send-email 2.50.0 In-Reply-To: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> References: <20260822062725.60519-1-muchamadcoirulanwar@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Add 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> 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) - Type-safe IioChanInfo enum dispatch in read_raw The AS5600 stores the 12-bit raw angle big-endian across registers 0x0C-0x0D. smbus_read_word_swapped() handles the byte swap: SMBus always transmits the low byte first (little-endian wire), so an unconditional byte swap recovers the correct value regardless of CPU endianness. The long-term solution is regmap-rs where endianness is configured once at the transport level. This driver uses INDIO_DIRECT_MODE without buffer or trigger support. All userspace access is through sysfs attributes, which ensures safe cleanup via kernfs_drain() synchronization in the IIO abstraction's PinnedDrop. See the module-level doc comment for details. Tested on BeagleBone Black (AM335x) with AS5600 on i2c-2 (0x36). Signed-off-by: Muchamad Coirul Anwar --- drivers/iio/position/Kconfig | 11 ++ drivers/iio/position/Makefile | 1 + drivers/iio/position/as5600.rs | 189 +++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+) create mode 100644 drivers/iio/position/as5600.rs diff --git a/drivers/iio/position/Kconfig b/drivers/iio/position/Kconfig index 1576a6380b53..ac4f19d61ff6 100644 --- a/drivers/iio/position/Kconfig +++ b/drivers/iio/position/Kconfig @@ -6,6 +6,17 @@ =20 menu "Linear and angular position sensors" =20 +config AS5600 + tristate "ams AS5600 magnetic rotary position sensor" + depends on I2C && 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 diff --git a/drivers/iio/position/Makefile b/drivers/iio/position/Makefile index d70902f2979d..2d26f6d6ace3 100644 --- a/drivers/iio/position/Makefile +++ b/drivers/iio/position/Makefile @@ -4,5 +4,6 @@ =20 # When adding new entries keep the list in alphabetical order =20 +obj-$(CONFIG_AS5600) +=3D as5600.o obj-$(CONFIG_HID_SENSOR_CUSTOM_INTEL_HINGE) +=3D hid-sensor-custom-intel-h= inge.o obj-$(CONFIG_IQS624_POS) +=3D iqs624-pos.o diff --git a/drivers/iio/position/as5600.rs b/drivers/iio/position/as5600.rs new file mode 100644 index 000000000000..8f2ea20a0645 --- /dev/null +++ b/drivers/iio/position/as5600.rs @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Muchamad Coirul Anwar +//! Driver for ams AS5600 12-bit magnetic rotary position sensor. +//! +//! This driver uses `INDIO_DIRECT_MODE` without buffer or trigger support. +//! All userspace access is through sysfs attributes (`in_angl_raw`, +//! `in_angl_scale`), which ensures safe cleanup via `kernfs_drain()` +//! synchronization in the IIO abstraction's `PinnedDrop`. +//! +//! Datasheet: https://look.ams-osram.com/m/7059eac7531a86fd/original/AS56= 00-DS000365.pdf + +use kernel::{ + bindings::{ + iio_chan_info_enum_IIO_CHAN_INFO_RAW, + iio_chan_info_enum_IIO_CHAN_INFO_SCALE, + iio_chan_spec, + iio_chan_type_IIO_ANGL, + INDIO_DIRECT_MODE, // + }, + bits::{ + bit_u8, + bit_usize, + genmask_u16, // + }, + device::{ + Bound, + Core, // + }, + error::code::ENODATA, + i2c::{ + DeviceId, + Driver, + I2cClient, + IdTable, // + }, + i2c_device_table, + iio::{ + Device, + IioChanInfo, + IioDriver, + IioVal, + Registered, // + }, + io::Io, + module_i2c_driver, + of, + of_device_table, + prelude::*, + sync::{ + aref::ARef, + new_mutex, + Mutex, // + }, // +}; + +const AS5600_REG_STATUS: u8 =3D 0x0B; +const AS5600_REG_RAW_ANGLE_H: u8 =3D 0x0C; + +const AS5600_STATUS_MD: u8 =3D bit_u8(5); +const AS5600_RAW_ANGLE_MASK: u16 =3D genmask_u16(0..=3D11); + +module_i2c_driver! { + type: As5600, + name: "as5600", + authors: ["Muchamad Coirul Anwar"], + description: "I2C Driver for ams OSRAM AS5600 Magnetic Rotary Position= Sensor", + license: "GPL", +} + +i2c_device_table!( + I2C_TABLE, + MODULE_I2C_TABLE, + ::IdInfo, + [(DeviceId::new(c"as5600"), ())] +); + +of_device_table!( + OF_TABLE, + MODULE_OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c"ams,as5600"), ())] +); + +struct As5600Channels([iio_chan_spec; 1]); + +// SAFETY: `iio_chan_spec` is a plain C struct with no interior mutability. +// All pointer fields (`event_spec`, `ext_info`, `extend_name`, etc.) are +// NULL =E2=80=94 set via `zeroed()` and never reassigned =E2=80=94 so no = shared mutable +// state exists behind them. The static is a compile-time constant with no +// `&mut` access path, making concurrent shared access safe. +unsafe impl Sync for As5600Channels {} + +static AS5600_CHANNELS: As5600Channels =3D As5600Channels({ + // SAFETY: `iio_chan_spec` is a repr(C) struct where all-zeroes is val= id + // (integers default to 0, pointers to NULL). + let mut chan: iio_chan_spec =3D unsafe { core::mem::zeroed() }; + chan.type_ =3D iio_chan_type_IIO_ANGL; + chan.info_mask_separate =3D bit_usize(iio_chan_info_enum_IIO_CHAN_INFO= _RAW) + | bit_usize(iio_chan_info_enum_IIO_CHAN_INFO_SCALE); + [chan] +}); + +#[pin_data] +struct As5600Priv { + #[pin] + io_lock: Mutex, +} + +struct As5600HwState { + client: ARef>, +} + +impl IioDriver for As5600Priv { + fn read_raw(&self, _chan: *const iio_chan_spec, info: IioChanInfo) -> = Result { + match info { + IioChanInfo::Raw =3D> { + let hw =3D self.io_lock.lock(); + let io =3D hw.client.smbus_io(); + // Read status register to verify magnet presence before + // reading the angle. + let status =3D io.try_read8(AS5600_REG_STATUS as usize)?; + + // Check magnet presence (MD bit). Without a magnet the an= gle + // register contains stale/invalid data. + if (status & AS5600_STATUS_MD) =3D=3D 0 { + return Err(ENODATA); + } + + // Word read at register 0x0C returns big-endian data. + // smbus_read_word_swapped() handles the byte swap. + // Mutex ensures status + angle read is atomic. + let raw =3D hw.client.smbus_read_word_swapped(AS5600_REG_R= AW_ANGLE_H)?; + let angle =3D raw & AS5600_RAW_ANGLE_MASK; + Ok(IioVal::Int(angle as i32)) + } + // Scale factor: radians per LSB =3D 2*pi / 4096 ~=3D 0.001533= 981 + IioChanInfo::Scale =3D> Ok(IioVal::IntPlusNano(0, 1533981)), + } + } + + fn channels(&self) -> &'static [iio_chan_spec] { + &AS5600_CHANNELS.0 + } +} + +#[pin_data] +struct As5600 { + #[pin] + _iio_dev: Device, +} + +impl Driver for As5600 { + type IdInfo =3D (); + type Data<'bound> =3D As5600; + + const I2C_ID_TABLE: Option> =3D Some(&I2C_TABLE); + const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); + + // `try_pin_init!` returns a concrete anonymous type that may expose m= ore + // bounds than the trait signature declares (e.g. auto-traits like `Se= nd`). + // This refinement of the RPITIT return type is intentional. + #[allow(refining_impl_trait)] + fn probe<'bound>( + dev: &'bound I2cClient>, + _id_info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit, Error> + 'bound { + try_pin_init!(As5600 { + _iio_dev: { + // Deref coercion: I2cClient> -> I2cClient. + // We capture the Bound context to call smbus_read_word_sw= apped() + // and try_read8(), which require Bound. + let bound: &I2cClient =3D dev; + let client: ARef> =3D ARef::from(bound); + + let priv_init =3D pin_init!(As5600Priv { + io_lock <- new_mutex!(As5600HwState { + client + }), + }); + + let iio_dev =3D + Device::build_device(dev.as_ref(), c"as5600", INDIO_DI= RECT_MODE, priv_init)?; + let registered =3D iio_dev.register(&crate::THIS_MODULE)?; + dev_dbg!(dev.as_ref(), "AS5600 magnetic position sensor re= ady\n"); + registered + } + }) + } +} --=20 2.50.0