Skip to contentSkip to conversation

rust: extend I2C functionality

PATCH In review Igor Korotin 6 participants 16 messages Jan 31 – Feb 9

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

cover rust: extend I2C functionality

This patch series extend the existing I2C functionality with:
- Abstractions allowing to implement I2C algorithms used by I2C adapters;
- Abstractions allowing to create and add new I2C adapters;
- Safe wrappers upon I2C and SMbus transferring C API: read/write bytes/words/byte arrays.

The patch series contains additional new sample driver rust_i2c_adapter presenting the new functionality.

Patch series depend on
message-id: <[email protected]>

---
Igor Korotin (5):
rust: i2c: split client and adapter code into separate files
rust: bits: add define_flags macro
rust: i2c: Add I2C Adapter registration abstractions
rust: i2c: add I2C wrappers
samples: rust: add Rust I2C adapter registration sample

 MAINTAINERS                      |   4 +-
 include/linux/i2c.h              |   6 +
 rust/helpers/helpers.c           |   1 +
 rust/helpers/i2c.c               |  15 ++
 rust/kernel/bits.rs              |  57 ++++++++
 rust/kernel/i2c.rs               | 254 ++-------------------------------
 rust/kernel/i2c/adapter.rs       | 200 ++++++++++++++++++++++++++
 rust/kernel/i2c/algo.rs          | 300 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/i2c/client.rs        | 284 ++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig             |  12 ++
 samples/rust/Makefile            |   1 +
 samples/rust/rust_driver_i2c.rs  |  10 +-
 samples/rust/rust_i2c_adapter.rs | 170 ++++++++++++++++++++++
 samples/rust/rust_i2c_client.rs  |  15 +-
 14 files changed, 1069 insertions(+), 260 deletions(-)

---
base-commit: a7c013f779530190d0c1e1aa5e7c8a61f0bd479e
change-id: 20260131-i2c-adapter-d38d330c4c25
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 6e4d28a06d842ddfc7db82f410532a35b8fe317d
prerequisite-patch-id: 9739295d85b688257fca29be1e1217a05a69c9e7
prerequisite-patch-id: 78eaed3746a40713f44f13508fcf43653b0a4528
prerequisite-patch-id: 99f1881bc896896297a903affcfa4f62cab1a307
prerequisite-patch-id: ea8baa9d648f1178d6f39d140b98bddf3c183f6f
prerequisite-patch-id: f8a9e049d204bde04e80151a67dfff5ec2633e7a

Best regards,

Signature · 1 line
Igor Korotin <[email protected]>
#1 lore raw

PATCH 1/5 rust: i2c: split client and adapter code into separate files

Reorganize the I2C module by splitting client-related and adapter-related code into separate files for better maintainability.

- Move client traits and implementations to i2c/client.rs
- Move adapter traits and implementations to i2c/adapter.rs

---
 MAINTAINERS                     |   1 +
 rust/kernel/i2c.rs              | 253 ++--------------------------------------
 rust/kernel/i2c/adapter.rs      |  80 +++++++++++++
 rust/kernel/i2c/client.rs       | 192 ++++++++++++++++++++++++++++++
 samples/rust/rust_driver_i2c.rs |  10 +-
 samples/rust/rust_i2c_client.rs |  15 ++-
 6 files changed, 293 insertions(+), 258 deletions(-)
MAINTAINERS +1 -0
index f6bc65de83c7..60662984176d 100644
@@ -11886,6 +11886,7 @@ R:	Danilo Krummrich <[email protected]>
 R:	Daniel Almeida <[email protected]>
 L:	[email protected]
 S:	Maintained
+F:	rust/i2c/*
 F:	rust/kernel/i2c.rs
 F:	samples/rust/rust_driver_i2c.rs
 F:	samples/rust/rust_i2c_client.rs
rust/kernel/i2c.rs +7 -246

287 lines not on this page · raw message

rust/kernel/i2c/adapter.rs new file +80 -0

80 lines not on this page · raw message

rust/kernel/i2c/client.rs new file +192 -0

192 lines not on this page · raw message

samples/rust/rust_driver_i2c.rs +4 -6
index 6be79f9e9fb5..af5e9aae4f06 100644
@@ -6,6 +6,7 @@
     acpi,
     device::Core,
     i2c,
+    i2c::client::I2cClient,
     of,
     prelude::*, //
 };
@@ -40,10 +41,7 @@ impl i2c::Driver for SampleDriver {
     const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE);
     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
 
-    fn probe(
-        idev: &i2c::I2cClient<Core>,
-        info: Option<&Self::IdInfo>,
-    ) -> impl PinInit<Self, Error> {
+    fn probe(idev: &I2cClient<Core>, info: Option<&Self::IdInfo>) -> impl PinInit<Self, Error> {
         let dev = idev.as_ref();
 
         dev_info!(dev, "Probe Rust I2C driver sample.\n");
@@ -55,11 +53,11 @@ fn probe(
         Ok(Self)
     }
 
-    fn shutdown(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn shutdown(idev: &I2cClient<Core>, _this: Pin<&Self>) {
         dev_info!(idev.as_ref(), "Shutdown Rust I2C driver sample.\n");
     }
 
-    fn unbind(idev: &i2c::I2cClient<Core>, _this: Pin<&Self>) {
+    fn unbind(idev: &I2cClient<Core>, _this: Pin<&Self>) {
         dev_info!(idev.as_ref(), "Unbind Rust I2C driver sample.\n");
     }
 }
samples/rust/rust_i2c_client.rs +9 -6
index 8d2c12e535b0..4b3dcf21230c 100644
@@ -71,7 +71,11 @@
     acpi,
     device,
     devres::Devres,
-    i2c,
+    i2c::{
+        adapter::I2cAdapter,
+        client::I2cBoardInfo,
+        client::Registration, //
+    }, //
     of,
     platform,
     prelude::*,
@@ -82,7 +86,7 @@
 struct SampleDriver {
     parent_dev: ARef<platform::Device>,
     #[pin]
-    _reg: Devres<i2c::Registration>,
+    _reg: Devres<Registration>,
 }
 
 kernel::of_device_table!(
@@ -101,8 +105,7 @@ struct SampleDriver {
 
 const SAMPLE_I2C_CLIENT_ADDR: u16 = 0x30;
 const SAMPLE_I2C_ADAPTER_INDEX: i32 = 0;
-const BOARD_INFO: i2c::I2cBoardInfo =
-    i2c::I2cBoardInfo::new(c"rust_driver_i2c", SAMPLE_I2C_CLIENT_ADDR);
+const BOARD_INFO: I2cBoardInfo = I2cBoardInfo::new(c"rust_driver_i2c", SAMPLE_I2C_CLIENT_ADDR);
 
 impl platform::Driver for SampleDriver {
     type IdInfo = ();
@@ -122,9 +125,9 @@ fn probe(
             parent_dev: pdev.into(),
 
             _reg <- {
-                let adapter = i2c::I2cAdapter::get(SAMPLE_I2C_ADAPTER_INDEX)?;
+                let adapter = I2cAdapter::get(SAMPLE_I2C_ADAPTER_INDEX)?;
 
-                i2c::Registration::new(&adapter, &BOARD_INFO, pdev.as_ref())
+                Registration::new(&adapter, &BOARD_INFO, pdev.as_ref())
             }
         })
     }
Signature · 1 line
2.43.0
#2 lore raw

PATCH 2/5 rust: bits: add define_flags macro

In reply to Igor Korotin

introduce define_flags macro that incorporates BitOr BitAnd and Not implementations.

---
 rust/kernel/bits.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
rust/kernel/bits.rs +57 -0
index 553d50265883..6750aef18708 100644
@@ -201,3 +201,60 @@ pub const fn [<genmask_ $ty>](range: RangeInclusive<u32>) -> $ty {
     /// assert_eq!(genmask_u8(0..=7), u8::MAX);
     /// ```
 );
+
+/// defines flags
+#[macro_export]
+macro_rules! define_flags {
+    (
+        $gen_name:ident($gen_type:ident),
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// Flags that can be combined with the operators `|`, `&`, and `!`.
+        ///
+        /// Values can be used from the [`flags`] module.
+        #[derive(Clone, Copy, PartialEq)]
+        pub struct $gen_name($gen_type);
+
+        impl $gen_name {
+            /// Get the raw representation of this flag.
+            pub(crate) fn as_raw(self) -> $gen_type {
+                self.0
+            }
+
+            /// Check whether `flags` is contained in `self`.
+            pub fn contains(self, flags: $gen_name) -> bool {
+                (self & flags) == flags
+            }
+        }
+
+        impl core::ops::BitOr for $gen_name {
+            type Output = $gen_name;
+            fn bitor(self, rhs: Self) -> Self::Output {
+                Self(self.0 | rhs.0)
+            }
+        }
+
+        impl core::ops::BitAnd for $gen_name {
+            type Output = $gen_name;
+            fn bitand(self, rhs: Self) -> Self::Output {
+                Self(self.0 & rhs.0)
+            }
+        }
+
+        impl core::ops::Not for $gen_name {
+            type Output = $gen_name;
+            fn not(self) -> Self::Output {
+                Self(!self.0)
+            }
+        }
+
+        #[allow(missing_docs)]
+        pub mod flags {
+            use super::$gen_name;
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: $gen_name = $gen_name($binding as $gen_type);
+            )+
+        }
+    }
+}
Signature · 1 line
2.43.0
#3 lore raw

Re: [PATCH 2/5] rust: bits: add define_flags macro

Igor,

Quoted 83 lines · On 31 Jan 2026, at 11:12, Igor Korotin via B4 Relay…

From: Igor Korotin <[email protected]>

introduce define_flags macro that incorporates BitOr BitAnd and Not implementations.

---
rust/kernel/bits.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++

1 file changed, 57 insertions(+)
rust/kernel/bits.rs +57 -0
index 553d50265883..6750aef18708 100644
@@ -201,3 +201,60 @@ pub const fn [<genmask_ $ty>](range: RangeInclusive<u32>) -> $ty {
    /// assert_eq!(genmask_u8(0..=7), u8::MAX);
    /// ```
 );
+
+/// defines flags
+#[macro_export]
+macro_rules! define_flags {
+    (
+        $gen_name:ident($gen_type:ident),
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// Flags that can be combined with the operators `|`, `&`, and `!`.
+        ///
+        /// Values can be used from the [`flags`] module.
+        #[derive(Clone, Copy, PartialEq)]
+        pub struct $gen_name($gen_type);
+
+        impl $gen_name {
+            /// Get the raw representation of this flag.
+            pub(crate) fn as_raw(self) -> $gen_type {
+                self.0
+            }
+
+            /// Check whether `flags` is contained in `self`.
+            pub fn contains(self, flags: $gen_name) -> bool {
+                (self & flags) == flags
+            }
+        }
+
+        impl core::ops::BitOr for $gen_name {
+            type Output = $gen_name;
+            fn bitor(self, rhs: Self) -> Self::Output {
+                Self(self.0 | rhs.0)
+            }
+        }
+
+        impl core::ops::BitAnd for $gen_name {
+            type Output = $gen_name;
+            fn bitand(self, rhs: Self) -> Self::Output {
+                Self(self.0 & rhs.0)
+            }
+        }
+
+        impl core::ops::Not for $gen_name {
+            type Output = $gen_name;
+            fn not(self) -> Self::Output {
+                Self(!self.0)
+            }
+        }
+
+        #[allow(missing_docs)]
+        pub mod flags {
+            use super::$gen_name;
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: $gen_name = $gen_name($binding as $gen_type);
+            )+
+        }
+    }
+}
Signature · 2 lines
-- 
2.43.0

Please drop this patch in favor of the patch from Filipe Xavier. It does the same thing.

— Daniel

#4 lore raw

PATCH 3/5 rust: i2c: Add I2C Adapter registration abstractions

In reply to Igor Korotin

Add safe Rust abstractions for I2C adapter registration and management, wrapping the C functions i2c_add_adapter and i2c_del_adapter.

This includes:
- Hide struct i2c_algorithm unions from bindgen to avoid unnecessary mangles.
- Safe wrappers upon struct i2c_msg and struct i2c_smbus_data
- I2C Algorithm wrapper around struct i2c_algorithm
- I2C Adapter Flags wrapper
- Registration/deregistration logic for I2C adapters

---
 include/linux/i2c.h        |   6 +
 rust/kernel/i2c.rs         |   1 +
 rust/kernel/i2c/adapter.rs | 120 ++++++++++++++++++
 rust/kernel/i2c/algo.rs    | 300 +++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 427 insertions(+)
include/linux/i2c.h +6 -0
index 20fd41b51d5c..c176243de254 100644
@@ -548,18 +548,24 @@ struct i2c_algorithm {
 	 * smbus_xfer. If set to NULL, the SMBus protocol is simulated
 	 * using common I2C messages.
 	 */
+#ifndef __BINDGEN__
 	union {
+#endif
 		int (*xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs,
 			    int num);
+#ifndef __BINDGEN__
 		int (*master_xfer)(struct i2c_adapter *adap, struct i2c_msg *msgs,
 				   int num);
 	};
 	union {
+#endif
 		int (*xfer_atomic)(struct i2c_adapter *adap,
 				   struct i2c_msg *msgs, int num);
+#ifndef __BINDGEN__
 		int (*master_xfer_atomic)(struct i2c_adapter *adap,
 					   struct i2c_msg *msgs, int num);
 	};
+#endif
 	int (*smbus_xfer)(struct i2c_adapter *adap, u16 addr,
 			  unsigned short flags, char read_write,
 			  u8 command, int size, union i2c_smbus_data *data);
rust/kernel/i2c.rs +1 -0
index 0bebfde3e495..af33a3be83c4 100644
@@ -19,6 +19,7 @@
 };
 
 pub mod adapter;
+pub mod algo;
 pub mod client;
 
 /// An I2C device id table.
rust/kernel/i2c/adapter.rs +120 -0

136 lines not on this page · raw message

rust/kernel/i2c/algo.rs new file +300 -0

300 lines not on this page · raw message

Signature · 1 line
2.43.0
#5 lore raw

PATCH 4/5 rust: i2c: add I2C wrappers

In reply to Igor Korotin

Add safe Rust wrappers for common I2C/SMbus operations on I2C clients.

These wrappers provide safe abstractions over low-level C API calls:
- SMbus byte operations: read/write byte and byte data
- SMbus word operations: read/write word data
- SMbus block operations: read/write I2C block data
- Master I2C operations: master receive and master send

All operations include proper error handling through the Result type.

---
 rust/helpers/helpers.c    |  1 +
 rust/helpers/i2c.c        | 15 ++++++++
 rust/kernel/i2c/client.rs | 92 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 108 insertions(+)
rust/helpers/helpers.c +1 -0
index 79c72762ad9c..6f6b0ff8713a 100644
@@ -29,6 +29,7 @@
 #include "err.c"
 #include "irq.c"
 #include "fs.c"
+#include "i2c.c"
 #include "io.c"
 #include "jump_label.c"
 #include "kunit.c"
rust/helpers/i2c.c new file +15 -0
new file mode 100644
index 000000000000..05bbd26eaaf8
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/i2c.h>
+
+__rust_helper int rust_helper_i2c_master_recv(const struct i2c_client *client,
+				  char *buf, int count)
+{
+	return i2c_master_recv(client, buf, count);
+}
+
+__rust_helper int rust_helper_i2c_master_send(const struct i2c_client *client,
+				  const char *buf, int count)
+{
+	return i2c_master_send(client, buf, count);
+}
rust/kernel/i2c/client.rs +92 -0

98 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH 4/5] rust: i2c: add I2C wrappers

Quoted 10 lines · On Sat, 2026-01-31 at 14:12 +0000, Igor Korotin via B4 Relay wrote:

From: Igor Korotin <[email protected]>

Add safe Rust wrappers for common I2C/SMbus operations on I2C clients.

These wrappers provide safe abstractions over low-level C API calls:
- SMbus byte operations: read/write byte and byte data
- SMbus word operations: read/write word data
- SMbus block operations: read/write I2C block data
- Master I2C operations: master receive and master send

Quoted 9 lines

All operations include proper error handling through the Result type.

---
 rust/helpers/helpers.c    |  1 +
 rust/helpers/i2c.c        | 15 ++++++++
 rust/kernel/i2c/client.rs | 92 +++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 108 insertions(+)

I think I2CClient should implement the IO [1] trait instead, as suggested by Danilo [2].

Also I think it is a little odd that read and write is possible, on I2CClient<Normal> and not I2CClient<Bound>. Shouldn't the assigned driver have exclusive read and write access to the device?

Thanks
- Markus Probst

[1]
https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git/commit/?h=driver-core-testing&id=121d87b28e1d9061d3aaa156c43a627d3cb5e620
[2]
https://lore.kernel.org/rust-for-linux/[email protected]/

maintainer
#7 lore raw

Re: [PATCH 4/5] rust: i2c: add I2C wrappers

Hello Markus

Quoted 2 lines · Markus Probst

I think I2CClient should implement the IO [1] trait instead, as suggested by Danilo [2].

I'm not sure it is appropriate to use IO and register! here. I2C devices
are different. Not all of them use register like access. For example EEPROM I2C devices allow random read/write operations inside their address space. After all I2C doesn't implement the same way of accessing its memory space as for example PCI devices.

Quoted 3 lines

Also I think it is a little odd that read and write is possible, on I2CClient<Normal> and not I2CClient<Bound>. Shouldn't the assigned driver have exclusive read and write access to the device?

Bound can be safely dereferenced to Normal. Since Normal represents the minimal required typestate for device operations, any API that works with Normal automatically works with Bound or Core as well. Requiring Bound would unnecessarily restrict the API and force duplication or unsafe casts.

Quoted 7 lines

Thanks
- Markus Probst

[1]
https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git/commit/?h=driver-core-testing&id=121d87b28e1d9061d3aaa156c43a627d3cb5e620
[2]
https://lore.kernel.org/rust-for-linux/[email protected]/

Cheers
Igor

maintainer
#8 lore raw

Re: [PATCH 4/5] rust: i2c: add I2C wrappers

Quoted 5 lines · Igor Korotin

I'm not sure it is appropriate to use IO and register! here. I2C devices are different. Not all of them use register like access. For example EEPROM I2C devices allow random read/write operations inside their address space. After all I2C doesn't implement the same way of accessing its memory space as for example PCI devices.

Conceptually, it is not different, it is some device memory connected through some bus.

Memory mapped I/O allows "random read/write operations" as well, see memcpy_fromio() and memcpy_toio().

The same thing is true for DMA memory. While it's not owned by the device, it's still shared with a device.

Gary just started working on a generic IoView<'io, T> type which will serve as a general abstraction to interact with any kind of memory that is shared between a device and the CPU [1].

So, for I2C this would mean that if you have register like accesses you can use the register!() abstractions. If you want random read/write operations, you can use IoView to copy from / to system memory or even to a user buffer directly.

Of course you can also still use Io::read32() and friends.

[1] https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/Generic.20I.2FO.20backends/with/571786051

maintainer
#9 lore raw

Re: [PATCH 4/5] rust: i2c: add I2C wrappers

Hello Danilo

Quoted 20 lines · Danilo Krummrich
Quoted 5 lines · Igor Korotin

I'm not sure it is appropriate to use IO and register! here. I2C devices are different. Not all of them use register like access. For example EEPROM I2C devices allow random read/write operations inside their address space. After all I2C doesn't implement the same way of accessing its memory space as for example PCI devices.

Conceptually, it is not different, it is some device memory connected through some bus.

Memory mapped I/O allows "random read/write operations" as well, see memcpy_fromio() and memcpy_toio().

The same thing is true for DMA memory. While it's not owned by the device, it's still shared with a device.

Gary just started working on a generic IoView<'io, T> type which will serve as a general abstraction to interact with any kind of memory that is shared between a device and the CPU [1].

Quoted 7 lines

So, for I2C this would mean that if you have register like accesses you can use the register!() abstractions. If you want random read/write operations, you can use IoView to copy from / to system memory or even to a user buffer directly.

Of course you can also still use Io::read32() and friends.

[1] https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/Generic.20I.2FO.20backends/with/571786051

thanks, that makes sense.

I don’t have a strong prior opinion on how this should look yet, so I’m fine aligning the I2C abstractions with the generic direction you describe. Using register!() for register-like accesses and IoView for more general read/write patterns seems reasonable.

At this point I’ll treat this as the intended model and adjust the I2C side accordingly once IoView is in place and its API settles.

Regards,
Igor

maintainer
#10 lore raw

Re: [PATCH 4/5] rust: i2c: add I2C wrappers

In reply to Igor Korotin
Quoted 5 lines · Igor Korotin

Bound can be safely dereferenced to Normal. Since Normal represents the minimal required typestate for device operations, any API that works with Normal automatically works with Bound or Core as well. Requiring Bound would unnecessarily restrict the API and force duplication or unsafe casts.

We cannot allow drivers to retain access to device resources of unbound devices. To prevent that we never give out a pci::Bar or IoMem instance without a Devres container.

#11 lore raw

PATCH 5/5 samples: rust: add Rust I2C adapter registration sample

In reply to Igor Korotin

Add a new rust_i2c_adapter sample, showing how to create a new i2c adapter using i2c::adapter::Registration

---
 MAINTAINERS                      |   3 +-
 samples/rust/Kconfig             |  12 +++
 samples/rust/Makefile            |   1 +
 samples/rust/rust_i2c_adapter.rs | 170 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 184 insertions(+), 2 deletions(-)
MAINTAINERS +1 -2
index 60662984176d..bae13f1f9a23 100644
@@ -11888,8 +11888,7 @@ L:	[email protected]
 S:	Maintained
 F:	rust/i2c/*
 F:	rust/kernel/i2c.rs
-F:	samples/rust/rust_driver_i2c.rs
-F:	samples/rust/rust_i2c_client.rs
+F:	samples/rust/rust_*i2c*.rs
 
 I2C SUBSYSTEM HOST DRIVERS
 M:	Andi Shyti <[email protected]>
samples/rust/Kconfig +12 -0
index 3efa51bfc8ef..a5157b50e27c 100644
@@ -107,6 +107,18 @@ config SAMPLE_RUST_I2C_CLIENT
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_I2C_ADAPTER
+	tristate "I2C Adapter Registration"
+	depends on I2C=y
+	help
+	  This option builds the Rust I2C adapter manual creation
+	  sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_i2c_adapter.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_DRIVER_PCI
 	tristate "PCI Driver"
 	depends on PCI
samples/rust/Makefile +1 -0
index f65885d1d62b..7026eb46ae50 100644
@@ -9,6 +9,7 @@ obj-$(CONFIG_SAMPLE_RUST_DEBUGFS_SCOPED)	+= rust_debugfs_scoped.o
 obj-$(CONFIG_SAMPLE_RUST_DMA)			+= rust_dma.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C)		+= rust_driver_i2c.o
 obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT)		+= rust_i2c_client.o
+obj-$(CONFIG_SAMPLE_RUST_I2C_ADAPTER)		+= rust_i2c_adapter.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_USB)		+= rust_driver_usb.o
samples/rust/rust_i2c_adapter.rs new file +170 -0

170 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#12 lore raw
In reply to Igor Korotin

(Cc: Bartosz, Greg, Rafael, driver-core)

Quoted 8 lines · On Sat Jan 31, 2026 at 3:12 PM CET, Igor Korotin via B4 Relay wrote:

This patch series extend the existing I2C functionality with:
- Abstractions allowing to implement I2C algorithms used by I2C adapters;
- Abstractions allowing to create and add new I2C adapters;
- Safe wrappers upon I2C and SMbus transferring C API: read/write bytes/words/byte arrays.

The patch series contains additional new sample driver rust_i2c_adapter presenting the new functionality.

The i2c_adapter code on the C side has some lifetime issues, Bartosz looks into resolving.

My biggest concern is that struct i2c_adapter is a bus device implementation, but does not use the reference count of the embedded struct device.

Instead, I2C bus drivers embedd the i2c_adapter in their driver specific structure, which is typically freed in the I2C bus driver's remove() callback.

This violates struct device reference counts.

Until this is fixed, the Rust abstractions should probably work around this, to subsequent painful rework.

Quoted 41 lines

Patch series depend on
message-id: <[email protected]>

---
Igor Korotin (5):
rust: i2c: split client and adapter code into separate files
rust: bits: add define_flags macro
rust: i2c: Add I2C Adapter registration abstractions
rust: i2c: add I2C wrappers
samples: rust: add Rust I2C adapter registration sample

 MAINTAINERS                      |   4 +-
 include/linux/i2c.h              |   6 +
 rust/helpers/helpers.c           |   1 +
 rust/helpers/i2c.c               |  15 ++
 rust/kernel/bits.rs              |  57 ++++++++
 rust/kernel/i2c.rs               | 254 ++-------------------------------
 rust/kernel/i2c/adapter.rs       | 200 ++++++++++++++++++++++++++
 rust/kernel/i2c/algo.rs          | 300 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/i2c/client.rs        | 284 ++++++++++++++++++++++++++++++++++++
 samples/rust/Kconfig             |  12 ++
 samples/rust/Makefile            |   1 +
 samples/rust/rust_driver_i2c.rs  |  10 +-
 samples/rust/rust_i2c_adapter.rs | 170 ++++++++++++++++++++++
 samples/rust/rust_i2c_client.rs  |  15 +-
 14 files changed, 1069 insertions(+), 260 deletions(-)

---
base-commit: a7c013f779530190d0c1e1aa5e7c8a61f0bd479e
change-id: 20260131-i2c-adapter-d38d330c4c25
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 6e4d28a06d842ddfc7db82f410532a35b8fe317d
prerequisite-patch-id: 9739295d85b688257fca29be1e1217a05a69c9e7
prerequisite-patch-id: 78eaed3746a40713f44f13508fcf43653b0a4528
prerequisite-patch-id: 99f1881bc896896297a903affcfa4f62cab1a307
prerequisite-patch-id: ea8baa9d648f1178d6f39d140b98bddf3c183f6f
prerequisite-patch-id: f8a9e049d204bde04e80151a67dfff5ec2633e7a

Best regards,

Signature · 1 line
Igor Korotin <[email protected]>
maintainer
#13 lore raw

Hello Danilo

Quoted 18 lines · Danilo Krummrich

(Cc: Bartosz, Greg, Rafael, driver-core)

Quoted 8 lines · On Sat Jan 31, 2026 at 3:12 PM CET, Igor Korotin via B4 Relay wrote:

This patch series extend the existing I2C functionality with:
- Abstractions allowing to implement I2C algorithms used by I2C adapters;
- Abstractions allowing to create and add new I2C adapters;
- Safe wrappers upon I2C and SMbus transferring C API: read/write bytes/words/byte arrays.

The patch series contains additional new sample driver rust_i2c_adapter presenting the new functionality.

The i2c_adapter code on the C side has some lifetime issues, Bartosz looks into resolving.

My biggest concern is that struct i2c_adapter is a bus device implementation, but does not use the reference count of the embedded struct device.

Quoted 7 lines

Instead, I2C bus drivers embedd the i2c_adapter in their driver specific structure, which is typically freed in the I2C bus driver's remove() callback.

This violates struct device reference counts.

Until this is fixed, the Rust abstractions should probably work around this, to subsequent painful rework.

just to clarify what is currently implemented on the Rust side.

The Rust I2cAdapter is required to be bound to a parent Device<Bound>. The implementation keeps a reference to the embedded struct device inside struct i2c_adapter for the entire lifetime of the Rust adapter, so its lifetime is tied to the device model.

I am not entirely sure which specific lifetime or refcounting scenario you are referring to. If you have a concrete case in mind where this would still be problematic, could you please point it out?

Cheers
Igor

maintainer
#14 lore raw
Quoted 31 lines · Igor Korotin

Hello Danilo

Quoted 18 lines · Danilo Krummrich

(Cc: Bartosz, Greg, Rafael, driver-core)

Quoted 8 lines · On Sat Jan 31, 2026 at 3:12 PM CET, Igor Korotin via B4 Relay wrote:

This patch series extend the existing I2C functionality with:
- Abstractions allowing to implement I2C algorithms used by I2C adapters;
- Abstractions allowing to create and add new I2C adapters;
- Safe wrappers upon I2C and SMbus transferring C API: read/write bytes/words/byte arrays.

The patch series contains additional new sample driver rust_i2c_adapter presenting the new functionality.

The i2c_adapter code on the C side has some lifetime issues, Bartosz looks into resolving.

My biggest concern is that struct i2c_adapter is a bus device implementation, but does not use the reference count of the embedded struct device.

Quoted 7 lines

Instead, I2C bus drivers embedd the i2c_adapter in their driver specific structure, which is typically freed in the I2C bus driver's remove() callback.

This violates struct device reference counts.

Until this is fixed, the Rust abstractions should probably work around this, to subsequent painful rework.

just to clarify what is currently implemented on the Rust side.

Quoted 8 lines

The Rust I2cAdapter is required to be bound to a parent Device<Bound>. The implementation keeps a reference to the embedded struct device inside struct i2c_adapter for the entire lifetime of the Rust adapter, so its lifetime is tied to the device model.

I am not entirely sure which specific lifetime or refcounting scenario you are referring to. If you have a concrete case in mind where this would still be problematic, could you please point it out?

The implementation on the C side does not consider the reference count of the embedded struct device, which is not correct.

#15 lore raw
In reply to Danilo Krummrich
Quoted 12 lines · Danilo Krummrich

(Cc: Bartosz, Greg, Rafael, driver-core)

Quoted 8 lines · On Sat Jan 31, 2026 at 3:12 PM CET, Igor Korotin via B4 Relay wrote:

This patch series extend the existing I2C functionality with:
- Abstractions allowing to implement I2C algorithms used by I2C adapters;
- Abstractions allowing to create and add new I2C adapters;
- Safe wrappers upon I2C and SMbus transferring C API: read/write bytes/words/byte arrays.

The patch series contains additional new sample driver rust_i2c_adapter presenting the new functionality.

Quoted 9 lines

The i2c_adapter code on the C side has some lifetime issues, Bartosz looks into resolving.

My biggest concern is that struct i2c_adapter is a bus device implementation, but does not use the reference count of the embedded struct device.

Instead, I2C bus drivers embedd the i2c_adapter in their driver specific structure, which is typically freed in the I2C bus driver's remove() callback.

Correct.

Quoted 2 lines

This violates struct device reference counts.

What's currently done in order to not crash is: we wait forever until all users release their references[1].

Quoted 3 lines

Until this is fixed, the Rust abstractions should probably work around this, to subsequent painful rework.

The rework of the C part will be long an painful already. I estimated the work will take at least a year. More info here[2].

Bart

[1] https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/i2c/i2c-core-base.c#n1814
[2] https://lore.kernel.org/all/aWYYZEPX-_1GfQtL@ninjato/