Skip to contentSkip to conversation

rust: i2c: Add basic I2C driver abstractions

PATCH Superseded Igor Korotin 3 participants 10 messages Sep 11, 2025 – Sep 27, 2025

Subsystems (3)

v5 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v5 cover rust: i2c: Add basic I2C driver abstractions

This patch series lays the groundwork for writing Linux I2C drivers in Rust by:

1. Core abstractions
Introduce i2c::I2cClient, i2c::I2cAdapter, i2c::Driver and built on the existing struct i2c_client, struct i2c_adapter and struct i2c_driver, with safe Rust wrappers around probe, transfer, and teardown logic.

2. Manual device creation
Provide an API to register an I2C device at runtime from Rust using I2cBoardInfo and I2cAdapter, including automatic cleanup when the driver unloads.

3. Sample driver (legacy table, OF & ACPI)
Add rust_driver_i2c, a sample that:
- creates an I2C client device using i2c::Registration::new()
- binds to an I2C client via:
- legacy I2C-ID table,
- Open Firmware (device-tree) compatible strings, or
- ACPI IDs.
- destroyes the I2C client device on exit.

Together, these three patches:

- Establish the essential Rust traits and types for I2C drivers.
- Enable driver binding via legacy ID table, device-tree (OF), or ACPI
- Enable manual device creation at runtime.
- Ship a samples showing typical usage

Igor Korotin (3):
rust: i2c: add basic I2C device and driver abstractions
rust: i2c: add manual I2C device creation abstractions
samples: rust: add Rust I2C sample driver

Changelog
---------
v5:
- Rename missed pdev variables to idev (thanks to Daniel).
- Import crate::device_id::RawDeviceIdIndex and
crate::types::AlwaysRefCounted in i2c.rs.
- Switch dev_dbg to dev_info in the sample I2C driver messages.
- Make I2cAdapter::get() return ARef<I2cAdapter> instead of
&I2cAdapter.
- Remove TryFrom<device::Device<Ctx>> for I2cAdapter<Ctx> (unused;
to be reintroduced in a later I2C series).
- Remove AsRef<device::Device<Ctx>> for I2cAdapter<Ctx> (unused;
to be reintroduced in a later I2C series).
- Add AsRef<I2cAdapter> for I2cAdapter<Ctx>.
- Use i2c_get/put_adapter instead of get/put_device for
AlwaysRefCounted<I2cAdapter>.
- Update safety comment for unsafe impl Sync for Registration {}.
- Tweak comment for I2cBoardInfo::new.
- Adjust build-time assertion message in Adapter::register.
- Link to v4: https://lore.kernel.org/rust-for-linux/[email protected]/
v4:
- Renamed i2c::I2cAdapterRef to i2c::I2cAdapter.
- Renamed i2c::Device to i2c::I2cClient for consistency with
i2c::I2cAdapter and to avoid confusion with i2c::Adapter
- Reworked i2c::I2cAdapter to be an Opaque around i2c_adapter struct
- Implemented AlwaysRefCounted trait for i2c::I2cAdapter.
- Fixed numerous comment mistakes and typos all over the code, thanks
to Danilo and Daniel
- Got rid of all unwrap() use-cases in i2c.rs and rust_driver_i2c.rs.
This covers 0-day kernel panic <[email protected]>
- Removed unnecessary casts.
- Replaced all addr_of_mut! macros to &raw mut.
- In i2c::Adapter::register method build assert if all ID tables are
None.
- Renamed all pdrv and pdev instances to idrv and idev respectivly
- Implemented an ealry return in i2c::Adapter::i2c_id_info
- Added all missing Safety comments.
- Removed unsafe impl<Ctx: device::DeviceContext> crate::types::AlwaysRefCounted for Device<Ctx> implementation which came to v3 from v2 by mistake.
- Added more details regarding i2c-stub driver usage in rust_driver_i2c
comment.
- Changed i2c::I2cAdapter::get return type from Option<Self> to
Result<&'static Self>.
- Added Daniel Almeida as a reviewer to the "I2C Subsystem [RUST]" entry
in MAINTAINERS, per his offer.
- Link to v3: https://lore.kernel.org/rust-for-linux/[email protected]/
v3:
- removed unnecessary i2c_get_clientdata and i2c_set_clientdata rust
helpers. Using generic accessors implemented in [1] instead.
- Reimplemented i2c::DeviceId based on changes in [2].
- Using from_result in i2c::Adapter::probe_callback
- Using explicit drop() for i2c client private data in
i2c::Adapter::remove_callback
- replaced device::Device::as_ref() with device::Device::from_raw in i2c::Device::as_ref(). It is renamed in device::Device.
- Build Rust I2C only if I2C is built-in
- Reimplement overcomplicated trait i2c::DeviceOwned the same way it is
implemented in auxiliary [3].
- Merge rust_device_i2c and rust_driver_i2c samples. Resulting
rust_driver_i2c creates pined i2c_client using i2c::Registration::new
and probes newly created i2c_client.
- Created a new entry in MAINTAINERS file containing i2c.rs and
rust_driver_i2c.rs in it.
- Link to v2: [4]

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
[3] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/rust/kernel/auxiliary.rs?h=v6.16-rc4#n299
[4] https://lore.kernel.org/rust-for-linux/[email protected]/

v2:
- Merged separated ACPI support patches since ACPI-table support is
merged into driver-core-next.
- Added I2cAdapterRef and I2cBoardInfo abstractions
- Added DeviceState generic parameter which is used for i2c::Device
as a sign if the device is created manually
- Added DeviceOwned abstraction which is a safe reference to a
manually created i2c::Device<Ctx, state::Owned>.
- Added Rust manual I2C device creation sample
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

 MAINTAINERS                     |   9 +
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/i2c.rs              | 547 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 samples/rust/Kconfig            |  11 +
 samples/rust/Makefile           |   1 +
 samples/rust/rust_driver_i2c.rs | 128 ++++++++
 7 files changed, 699 insertions(+)
 create mode 100644 rust/kernel/i2c.rs
 create mode 100644 samples/rust/rust_driver_i2c.rs

base-commit: 8f5ae30d69d7543eee0d70083daf4de8fe15d585

Signature · 1 line
2.43.0
#1 lore raw

PATCH v5 1/3 rust: i2c: add basic I2C device and driver abstractions

Implement the core abstractions needed for I2C drivers, including:

* i2c::Driver — the trait drivers must implement, including probe

* i2c::I2cClient — a safe wrapper around struct i2c_client

* i2c::Adapter — implements driver::RegistrationOps to hook into the generic driver::Registration machinery

* i2c::DeviceId — a RawDeviceIdIndex implementation for I2C device IDs

---
 MAINTAINERS                     |   8 +
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/i2c.rs              | 396 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 4 files changed, 407 insertions(+)
 create mode 100644 rust/kernel/i2c.rs
MAINTAINERS +8 -0
index fe168477caa4..c44c7ac317b1 100644
@@ -11516,6 +11516,14 @@ F:	include/linux/i2c.h
 F:	include/uapi/linux/i2c-*.h
 F:	include/uapi/linux/i2c.h
 
+I2C SUBSYSTEM [RUST]
+M:	Igor Korotin <[email protected]>
+R:	Danilo Krummrich <[email protected]>
+R:	Daniel Almeida <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/i2c.rs
+
 I2C SUBSYSTEM HOST DRIVERS
 M:	Andi Shyti <[email protected]>
 L:	[email protected]
rust/bindings/bindings_helper.h +1 -0
index 84d60635e8a9..81796d5e16e8 100644
@@ -53,6 +53,7 @@
 #include <linux/file.h>
 #include <linux/firmware.h>
 #include <linux/fs.h>
+#include <linux/i2c.h>
 #include <linux/ioport.h>
 #include <linux/jiffies.h>
 #include <linux/jump_label.h>
rust/kernel/i2c.rs new file +396 -0

396 lines not on this page · raw message

rust/kernel/lib.rs +2 -0
index ed53169e795c..a5e97a9b1546 100644
@@ -89,6 +89,8 @@
 pub mod firmware;
 pub mod fmt;
 pub mod fs;
+#[cfg(CONFIG_I2C = "y")]
+pub mod i2c;
 pub mod init;
 pub mod io;
 pub mod ioctl;
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v5 1/3] rust: i2c: add basic I2C device and driver abstractions

Hi Igor,

Quoted 6 lines · Igor Korotin

Implement the core abstractions needed for I2C drivers, including:

* i2c::Driver — the trait drivers must implement, including probe

Quoted 8 lines

* i2c::I2cClient — a safe wrapper around struct i2c_client

* i2c::Adapter — implements driver::RegistrationOps to hook into the generic driver::Registration machinery

* i2c::DeviceId — a RawDeviceIdIndex implementation for I2C device IDs

I’m a bit swamped for the next 2-3 days, but I will review this soon.

Feel free to ping me otherwise.

— Daniel

#3 lore raw

Re: [PATCH v5 1/3] rust: i2c: add basic I2C device and driver abstractions

In reply to Igor Korotin
Quoted 20 lines · Igor Korotin
rust/kernel/i2c.rs new file +20 -0
+pub trait Driver: Send {
+    /// The type holding information about each device id supported by the driver.
+    // TODO: Use `associated_type_defaults` once stabilized:
+    //
+    // ```
+    // type IdInfo: 'static = ();
+    // ```
+    type IdInfo: 'static;
+
+    /// The table of device ids supported by the driver.
+    const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = None;
+
+    /// The table of OF device ids supported by the driver.
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
+
+    /// The table of ACPI device ids supported by the driver.
+    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
+
+    /// I2C driver probe.
+    ///

rust/kernel/i2c.rs line 313

Quoted 10 lines
rust/kernel/i2c.rs new file +10 -0
+    /// Called when a new i2c client is added or discovered.
+    /// Implementers should attempt to initialize the client here.
+    fn probe(
+        dev: &I2cClient<device::Core>,
+        id_info: Option<&Self::IdInfo>,
+    ) -> Result<Pin<KBox<Self>>>;
+
+    /// I2C driver shutdown
+    ///
+    /// Called when

Seems like you did forget to actually finish the comment.

Quoted 1 line

+ fn shutdown(dev: &I2cClient<device::Core>) {

You should also provide a Pin<&Self> argument.

Review

Quoted 2 lines
(quoted diff) +2 -0
+        let _ = dev;
+    }

Can you please also add an unbind() method analogous to PCI, platform, etc.? It avoids that people have to use try_access() for accessing device resources on remove().

#4 lore raw

PATCH v5 2/3 rust: i2c: add manual I2C device creation abstractions

In reply to Igor Korotin

In addition to the basic I2C device support, add rust abstractions upon i2c_new_client_device/i2c_unregister_device C functions.

Implement the core abstractions needed for manual creation/deletion of I2C devices, including:

* i2c::Registration — a NonNull pointer created by the function

                          `i2c_new_client_device`

* i2c::I2cAdapter — a ref counted wrapper around struct i2c_adapter

* i2c::I2cBoardInfo — a safe wrapper around struct i2c_board_info

---
 rust/kernel/i2c.rs | 153 ++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 152 insertions(+), 1 deletion(-)
rust/kernel/i2c.rs +152 -1
index c17665cd5662..97865a9d8fea 100644
@@ -13,7 +13,12 @@
     types::{AlwaysRefCounted, Opaque},
 };
 
-use core::{marker::PhantomData, ptr::NonNull};
+use core::{
+    marker::PhantomData,
+    ptr::{from_ref, NonNull},
+};
+
+use kernel::types::ARef;
 
 /// An I2C device id table.
 #[repr(transparent)]
@@ -316,6 +321,110 @@ fn shutdown(dev: &I2cClient<device::Core>) {
     }
 }
 
+/// The i2c adapter representation.
+///
+/// This structure represents the Rust abstraction for a C `struct i2c_adapter`. The
+/// implementation abstracts the usage of an existing C `struct i2c_adapter` that
+/// gets passed from the C side
+///
+/// # Invariants
+///
+/// A [`I2cAdapter`] instance represents a valid `struct i2c_adapter` created by the C portion of
+/// the kernel.
+#[repr(transparent)]
+pub struct I2cAdapter<Ctx: device::DeviceContext = device::Normal>(
+    Opaque<bindings::i2c_adapter>,
+    PhantomData<Ctx>,
+);
+
+impl<Ctx: device::DeviceContext> I2cAdapter<Ctx> {
+    fn as_raw(&self) -> *mut bindings::i2c_adapter {
+        self.0.get()
+    }
+}
+
+impl I2cAdapter {
+    /// Gets pointer to an `i2c_adapter` by index.
+    pub fn get(index: i32) -> Result<ARef<Self>> {
+        // SAFETY: `index` must refer to a valid I2C adapter; the kernel
+        // guarantees that `i2c_get_adapter(index)` returns either a valid
+        // pointer or NULL. `NonNull::new` guarantees the correct check.
+        let adapter = NonNull::new(unsafe { bindings::i2c_get_adapter(index) }).ok_or(ENODEV)?;
+
+        // SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.
+        // `I2cAdapter` is #[repr(transparent)], so this cast is valid.
+        Ok(unsafe { (&*adapter.as_ptr().cast::<I2cAdapter<device::Normal>>()).into() })
+    }
+}
+
+impl<Ctx: device::DeviceContext> Drop for I2cAdapter<Ctx> {
+    fn drop(&mut self) {
+        // SAFETY: This `I2cAdapter` was obtained from `i2c_get_adapter`,
+        // and calling `i2c_put_adapter` exactly once will correctly release
+        // the reference count in the I2C core. It is safe to call from any context
+        unsafe { bindings::i2c_put_adapter(self.as_raw()) }
+    }
+}
+
+// SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't depend on `I2cAdapter`'s generic
+// argument.
+kernel::impl_device_context_deref!(unsafe { I2cAdapter });
+kernel::impl_device_context_into_aref!(I2cAdapter);
+
+// SAFETY: Instances of `I2cAdapter` are always reference-counted.
+unsafe impl crate::types::AlwaysRefCounted for I2cAdapter {
+    fn inc_ref(&self) {
+        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
+        unsafe { bindings::i2c_get_adapter((*self.as_raw()).nr) };
+    }
+
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
+        unsafe { bindings::i2c_put_adapter(&raw mut (*obj.as_ref().as_raw())) }
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<I2cAdapter<Ctx>> for I2cAdapter<Ctx> {
+    fn as_ref(&self) -> &I2cAdapter<Ctx> {
+        &self
+    }
+}
+
+/// The i2c board info representation
+///
+/// This structure represents the Rust abstraction for a C `struct i2c_board_info` structure,
+/// which is used for manual I2C client creation.
+#[repr(transparent)]
+pub struct I2cBoardInfo(bindings::i2c_board_info);
+
+impl I2cBoardInfo {
+    const I2C_TYPE_SIZE: usize = 20;
+    /// Create a new [`I2cBoardInfo`] for a kernel driver.
+    #[inline(always)]
+    pub const fn new(type_: &'static CStr, addr: u16) -> Self {
+        build_assert!(
+            type_.len_with_nul() <= Self::I2C_TYPE_SIZE,
+            "Type exceeds 20 bytes"
+        );
+        let src = type_.as_bytes_with_nul();
+        // Replace with `bindings::acpi_device_id::default()` once stabilized for `const`.
+        // SAFETY: FFI type is valid to be zero-initialized.
+        let mut i2c_board_info: bindings::i2c_board_info = unsafe { core::mem::zeroed() };
+        let mut i: usize = 0;
+        while i < src.len() {
+            i2c_board_info.type_[i] = src[i];
+            i += 1;
+        }
+
+        i2c_board_info.addr = addr;
+        Self(i2c_board_info)
+    }
+
+    fn as_raw(&self) -> *const bindings::i2c_board_info {
+        from_ref(&self.0)
+    }
+}
+
 /// The i2c client representation.
 ///
 /// This structure represents the Rust abstraction for a C `struct i2c_client`. The
@@ -394,3 +503,45 @@ unsafe impl Send for I2cClient {}
 // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`
 // (i.e. `I2cClient<Normal>) are thread safe.
 unsafe impl Sync for I2cClient {}
+
+/// The registration of an i2c client device.
+///
+/// This type represents the registration of a [`struct i2c_client`]. When an instance of this
+/// type is dropped, its respective i2c client device will be unregistered from the system.
+///
+/// # Invariants
+///
+/// `self.0` always holds a valid pointer to an initialized and registered
+/// [`struct i2c_client`].
+#[repr(transparent)]
+pub struct Registration(NonNull<bindings::i2c_client>);
+
+impl Registration {
+    /// The C `i2c_new_client_device` function wrapper for manual I2C client creation.
+    pub fn new(i2c_adapter: &I2cAdapter, i2c_board_info: &I2cBoardInfo) -> Result<Self> {
+        // SAFETY: the kernel guarantees that `i2c_new_client_device()` returns either a valid
+        // pointer or NULL. `from_err_ptr` separates errors. Following `NonNull::new` checks for NULL.
+        let raw_dev = from_err_ptr(unsafe {
+            bindings::i2c_new_client_device(i2c_adapter.as_raw(), i2c_board_info.as_raw())
+        })?;
+
+        let dev_ptr = NonNull::new(raw_dev).ok_or(ENODEV)?;
+
+        Ok(Self(dev_ptr))
+    }
+}
+
+impl Drop for Registration {
+    fn drop(&mut self) {
+        // SAFETY: `Drop` is only called for a valid `Registration`, which by invariant
+        // always contains a non-null pointer to an `i2c_client`.
+        unsafe { bindings::i2c_unregister_device(self.0.as_ptr()) }
+    }
+}
+
+// SAFETY: A `Registration` of a `struct i2c_client` can be released from any thread.
+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 {}
Signature · 1 line
2.43.0
#5 lore raw

Re: [PATCH v5 2/3] rust: i2c: add manual I2C device creation abstractions

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 348

Quoted 3 lines · Igor Korotin
rust/kernel/i2c.rs +3 -0
+impl I2cAdapter {
+    /// Gets pointer to an `i2c_adapter` by index.
+    pub fn get(index: i32) -> Result<ARef<Self>> {

Where do we get this index usually from? OF, ACPI, etc. I assume? I feel like it could make sense to wrap it into a new type. Even though it is not safety relevant it eliminates a source for mistakes.

Quoted 9 lines
rust/kernel/i2c.rs +9 -0
+        // SAFETY: `index` must refer to a valid I2C adapter; the kernel
+        // guarantees that `i2c_get_adapter(index)` returns either a valid
+        // pointer or NULL. `NonNull::new` guarantees the correct check.
+        let adapter = NonNull::new(unsafe { bindings::i2c_get_adapter(index) }).ok_or(ENODEV)?;
+
+        // SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.
+        // `I2cAdapter` is #[repr(transparent)], so this cast is valid.
+        Ok(unsafe { (&*adapter.as_ptr().cast::<I2cAdapter<device::Normal>>()).into() })
+    }

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 367

Quoted 10 lines
rust/kernel/i2c.rs +10 -0
+}
+
+impl<Ctx: device::DeviceContext> Drop for I2cAdapter<Ctx> {
+    fn drop(&mut self) {
+        // SAFETY: This `I2cAdapter` was obtained from `i2c_get_adapter`,
+        // and calling `i2c_put_adapter` exactly once will correctly release
+        // the reference count in the I2C core. It is safe to call from any context
+        unsafe { bindings::i2c_put_adapter(self.as_raw()) }
+    }
+}

The Drop implementation is not needed, you only ever give out an ARef<I2cAdapter>, but never a "raw" I2cAdapter, which is the correct thing to do.

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 378

Quoted 11 lines
rust/kernel/i2c.rs +11 -0
+
+// SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't depend on `I2cAdapter`'s generic
+// argument.
+kernel::impl_device_context_deref!(unsafe { I2cAdapter });
+kernel::impl_device_context_into_aref!(I2cAdapter);
+
+// SAFETY: Instances of `I2cAdapter` are always reference-counted.
+unsafe impl crate::types::AlwaysRefCounted for I2cAdapter {
+    fn inc_ref(&self) {
+        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
+        unsafe { bindings::i2c_get_adapter((*self.as_raw()).nr) };

Please make accessing the nr field a separate inline function, or at least put it in a separate unsafe block.

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 383

Quoted 5 lines
rust/kernel/i2c.rs +5 -0
+    }
+
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
+        unsafe { bindings::i2c_put_adapter(&raw mut (*obj.as_ref().as_raw())) }

Same here, separate unsafe blocks please.

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 391

Quoted 8 lines
rust/kernel/i2c.rs +8 -0
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<I2cAdapter<Ctx>> for I2cAdapter<Ctx> {
+    fn as_ref(&self) -> &I2cAdapter<Ctx> {
+        &self
+    }
+}

This AsRef implementation doesn't seem to do anything?

#6 lore raw

Re: [PATCH v5 2/3] rust: i2c: add manual I2C device creation abstractions

Hello Danilo

Quoted 8 lines · Danilo Krummrich

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 348

Quoted 3 lines · Igor Korotin
rust/kernel/i2c.rs +3 -0
+impl I2cAdapter {
+    /// Gets pointer to an `i2c_adapter` by index.
+    pub fn get(index: i32) -> Result<ARef<Self>> {

Where do we get this index usually from? OF, ACPI, etc. I assume? I feel like it could make sense to wrap it into a new type. Even though it is not safety relevant it eliminates a source for mistakes.

It usually comes as predefined magic number in a platform driver info. I'll define a specific type for this number for clearance.

Quoted 10 lines

rust/kernel/i2c.rs fn shutdown(dev: &I2cClient<device::Core>) { · line 391

Quoted 8 lines
rust/kernel/i2c.rs +8 -0
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<I2cAdapter<Ctx>> for I2cAdapter<Ctx> {
+    fn as_ref(&self) -> &I2cAdapter<Ctx> {
+        &self
+    }
+}

This AsRef implementation doesn't seem to do anything?

I misunderstood the concept of the ARef<T> a little bit and used this as_ref() instead of just getting a reference by &adapter. I'll remove this in the next drop

Thanks for the review. All other comments are noted. I'll address them in the next drop as well

Cheers
Igor

#7 lore raw

PATCH v5 3/3 samples: rust: add Rust I2C sample driver

In reply to Igor Korotin

Add a new rust_driver_i2c sample, showing how to create a new i2c client using i2c::Registration and bind a driver to it via legacy I2C-ID table.

---
 MAINTAINERS                     |   1 +
 samples/rust/Kconfig            |  11 +++
 samples/rust/Makefile           |   1 +
 samples/rust/rust_driver_i2c.rs | 128 ++++++++++++++++++++++++++++++++
 4 files changed, 141 insertions(+)
 create mode 100644 samples/rust/rust_driver_i2c.rs
MAINTAINERS +1 -0
index c44c7ac317b1..2654a7ea0c80 100644
@@ -11523,6 +11523,7 @@ R:	Daniel Almeida <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	rust/kernel/i2c.rs
+F:	samples/rust/rust_driver_i2c.rs
 
 I2C SUBSYSTEM HOST DRIVERS
 M:	Andi Shyti <[email protected]>
samples/rust/Kconfig +11 -0
index 7f7371a004ee..28dae070b365 100644
@@ -62,6 +62,17 @@ config SAMPLE_RUST_DMA
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DRIVER_I2C
+	tristate "I2C Driver"
+	depends on I2C=y
+	help
+	  This option builds the Rust I2C driver sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_driver_i2c.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index bd2faad63b4f..141d8f078248 100644
@@ -5,6 +5,7 @@ obj-$(CONFIG_SAMPLE_RUST_MINIMAL)		+= rust_minimal.o
 obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE)		+= rust_misc_device.o
 obj-$(CONFIG_SAMPLE_RUST_PRINT)			+= rust_print.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
+obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C)		+= rust_driver_i2c.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
samples/rust/rust_driver_i2c.rs new file +128 -0

128 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

Re: [PATCH v5 3/3] samples: rust: add Rust I2C sample driver

samples/rust/rust_driver_i2c.rs line 98

Quoted 5 lines · Igor Korotin
samples/rust/rust_driver_i2c.rs new file +5 -0
+// NOTE: The code below is expanded macro module_i2c_driver. It is not used here
+//       because we need to manually create an I2C client in `init()`. The macro
+//       hides `init()`, so to demo client creation on adapter SAMPLE_I2C_ADAPTER_INDEX
+//       we expand it by hand.
+type Ops<T> = kernel::i2c::Adapter<T>;

Not a huge fan of this type alias, but up to you. :)

Quoted 4 lines
samples/rust/rust_driver_i2c.rs new file +4 -0
+#[pin_data]
+struct DriverModule {
+    #[pin]
+    _driver: kernel::driver::Registration<Ops<SampleDriver>>,

samples/rust/rust_driver_i2c.rs line 113

Quoted 10 lines
samples/rust/rust_driver_i2c.rs new file +10 -0
+    _reg: i2c::Registration,
+}
+
+impl kernel::InPlaceModule for DriverModule {
+    fn init(
+        module: &'static kernel::ThisModule,
+    ) -> impl ::pin_init::PinInit<Self, kernel::error::Error> {
+        kernel::try_pin_init!(Self {
+            _reg <- {
+                let adapter = i2c::I2cAdapter::<Normal>::get(SAMPLE_I2C_ADAPTER_INDEX)?;

Just i2c::I2cAdapter::get() is fine.

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+                i2c::Registration::new(adapter.as_ref(), &BOARD_INFO)

Does i2c_new_client_device() grab a reference count of the adapter? If not, you have to store an ARef<I2cAdapter> within your i2c::Registration as well.

Quoted 5 lines
samples/rust/rust_driver_i2c.rs new file +5 -0
+            },
+            _driver <- kernel::driver::Registration::new(<Self as kernel::ModuleMetadata>::NAME,module,),
+        })
+    }
+}
#9 lore raw

Re: [PATCH v5 3/3] samples: rust: add Rust I2C sample driver

Hello Danilo

Quoted 8 lines · Danilo Krummrich

samples/rust/rust_driver_i2c.rs line 98

Quoted 5 lines · Igor Korotin
samples/rust/rust_driver_i2c.rs new file +5 -0
+// NOTE: The code below is expanded macro module_i2c_driver. It is not used here
+//       because we need to manually create an I2C client in `init()`. The macro
+//       hides `init()`, so to demo client creation on adapter SAMPLE_I2C_ADAPTER_INDEX
+//       we expand it by hand.
+type Ops<T> = kernel::i2c::Adapter<T>;

Not a huge fan of this type alias, but up to you. :)

I literally just unwrapped module_driver! macro to get to the init function. This type was part of that macro. I do not see it necessary, so I'll remove it in the next drop.

Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+                i2c::Registration::new(adapter.as_ref(), &BOARD_INFO)

Does i2c_new_client_device() grab a reference count of the adapter? If not, you have to store an ARef<I2cAdapter> within your i2c::Registration as well.

Well, as far as I traced the C code, adapter->dev is a client->dev->parent. Inside of the i2c_new_client_device the new created client device is being registered and as part of this registration device's parent reference count is being incremented.

A big thanks for the review and comments.

Regards
Igor