rust: i2c: Add basic I2C driver abstractions
Subsystems (3)
v7 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 I2C driver (legacy table, OF & ACPI)
Add rust_driver_i2c, a sample that:
- binds to an I2C client via:
- legacy I2C-ID table,
- Open Firmware (device-tree) compatible strings, or
- ACPI IDs.
4. Sample I2C client registration (OF & ACPI)
Add rust_i2c_client, a sample that:
- binds to a platform parent device using OF/ACPI table
- registers new I2C client bound to the parent platform device using i2c::Registration::new()
- destroyes the I2C client device on exit.
Together, these four 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 (4):
rust: i2c: add basic I2C device and driver abstractions
rust: i2c: add manual I2C device creation abstractions
samples: rust: add Rust I2C sample driver
samples: rust: add Rust I2C client registration sample
Changelog
---------
v7:
- Rebase and update i2c::Driver::probe function based on patch series [1].
- use i2c::Driver::unbind instead of drop in i2c::Adapter::remove_callback
- Implement and use i2c::Driver::unbind for I2C SampleDriver instead of Drop.
- i2c::Registration::new requires a parent device to which a new I2C client will be bound.
- i2c::Registration::new returns impl PinInit<Devres<Self>, Error>
- The existing rust_driver_i2c sample has been split into two:
rust_driver_i2c, which demonstrates the implementation of an I2C driver, and rust_i2c_client, which demonstrates registering a new I2C client bound to a parent platform device.
- Link to v6: [2]
[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/rust-for-linux/[email protected]/
v6:
- Add implementation of unbind for i2c::Driver trait;
- Add argument Pin<&Self> to i2c::Driver::shutdown method;
- Adjust usage of i2c::Driver::shutdown in
i2c::Adapter::shutdown_callback in i2c::Driver trait code
example and in rust_driver_i2c code;
- Remove dummy AsRef implementation for I2cAdapter. Adjust code
in rust_driver_i2c;
- Add i2c::I2cAdapter::get_nr method that returns I2cAdapter index;
- Optimize unsafe sections in inc_ref/dec_ref in AlwaysRefCounted
for I2cAdapter implementation;
- Remove unnecessary Drop implementation for I2cAdapter, because
I2cAdapter is always a reference;
- Remove unnecessary type definition Ops<T> in rust_driver_i2c
- Simplify call of i2c::I2cAdapter::get in try_pin_init! macro
for rust_driver_i2c
- Link to v5: https://lore.kernel.org/rust-for-linux/[email protected]/
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 | 576 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + samples/rust/Kconfig | 23 ++ samples/rust/Makefile | 2 + samples/rust/rust_driver_i2c.rs | 69 ++++ samples/rust/rust_i2c_client.rs | 142 ++++++++ 8 files changed, 824 insertions(+) create mode 100644 rust/kernel/i2c.rs create mode 100644 samples/rust/rust_driver_i2c.rs create mode 100644 samples/rust/rust_i2c_client.rs
base-commit: 8f3d55856900d0fd87aa8f4f2cac10320485dd38
Signature · 1 line
2.43.0
PATCH v7 1/4 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 | 425 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 436 insertions(+) create mode 100644 rust/kernel/i2c.rs
MAINTAINERS +8 -0
@@ -11737,6 +11737,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
@@ -58,6 +58,7 @@#include <linux/firmware.h> #include <linux/interrupt.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 +425 -0
425 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -94,6 +94,8 @@pub mod firmware;pub mod fmt;pub mod fs; +#[cfg( CONFIG_I2C = "y" )] +pub mod i2c;pub mod id_pool;pub mod init;pub mod io;
Signature · 1 line
2.43.0
Danilo Krummrich
reviewerRe: [PATCH v7 1/4] rust: i2c: add basic I2C device and driver abstractions
Quoted 12 lines · Igor Korotin
rust/kernel/i2c.rs new file +6
-0@@ -0,0 +1,425 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! I2C Driver subsystem + +// I2C Driver abstractions. +use crate ::{
rust/kernel/i2c.rs line 16
Quoted 10 lines
rust/kernel/i2c.rs new file +10
-0+ acpi, container_of, device, + device_id::{RawDeviceId, RawDeviceIdIndex}, + driver, + error::*, + of, + prelude::*, + types::{AlwaysRefCounted, Opaque}, +}; + +use core::{marker::PhantomData , ptr::NonNull };
Please use kernel "vertical style" [1].
[1] https://docs.kernel.org/rust/coding-guidelines.html#imports
Please also run ./scripts/checkpatch.pl on all patches, there are a few warnings to address.
Quoted 10 lines
rust/kernel/i2c.rs new file +10
-0+ +/// An I2C device id table. +#[repr(transparent)] +#[derive( Clone , Copy )] +pub struct DeviceId (bindings::i2c_device_id ); + +impl DeviceId { +const I2C_NAME_SIZE :usize =20 ; + +/// Create a new device id from an I2C 'id' string.
rust/kernel/i2c.rs line 36
Quoted 10 lines
rust/kernel/i2c.rs new file +10
-0+#[inline(always)] +pub const fn new (id: &'staticCStr ) ->Self { +build_assert! ( + id.len_with_nul () <=Self ::I2C_NAME_SIZE , +"ID exceeds 20 bytes" + ); +let src = id.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: bindings::i2c_device_id =unsafe { core::mem::zeroed () };
You can use pin_init::zeroed() for this.
Quoted 9 lines
rust/kernel/i2c.rs new file +9
-0+let mut i =0 ; +while i < src.len () { + i2c.name[i] = src[i]; + i +=1 ; + } + +Self (i2c) + } +}
PATCH v7 1/4 rust: i2c: add basic I2C device and driver abstractions
In reply to Igor KorotinImplement 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 | 425 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 436 insertions(+) create mode 100644 rust/kernel/i2c.rs
MAINTAINERS +8 -0
@@ -11737,6 +11737,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
@@ -58,6 +58,7 @@#include <linux/firmware.h> #include <linux/interrupt.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 +425 -0
425 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -94,6 +94,8 @@pub mod firmware;pub mod fmt;pub mod fs; +#[cfg( CONFIG_I2C = "y" )] +pub mod i2c;pub mod id_pool;pub mod init;pub mod io;
Signature · 1 line
2.43.0
PATCH v7 2/4 rust: i2c: add manual I2C device creation abstractions
In reply to Igor KorotinIn 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
@@ -6,6 +6,7 @@use crate ::{ acpi, container_of, device, device_id::{RawDeviceId ,RawDeviceIdIndex }, + devres::Devres , driver, error::*, of,
@@ -13,7 +14,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)]
@@ -345,6 +351,101 @@ fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) { } } +/// 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 { +/// Returns the I2C Adapter index. +#[inline] +pub fn get_nr (&self) ->i32 { +// SAFETY: `self.as_raw` is a valid pointer to a `struct i2c_adapter`. +unsafe { (*self.as_raw ()).nr } + } +/// 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 () }) + } +} + +// 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.get_nr ()) }; + } + +unsafe fn dec_ref (obj:NonNull <Self >) { +// SAFETY: The safety requirements guarantee that the refcount is non-zero. +unsafe { bindings::i2c_put_adapter (obj.as_ref ().as_raw ()) } + } +} + +/// 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_: &'staticCStr , 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
@@ -423,3 +524,53 @@ 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 <'a>( + i2c_adapter: &I2cAdapter , + i2c_board_info: &I2cBoardInfo , + parent_dev: &'a device::Device <device::Bound >, + ) ->impl PinInit <Devres <Self >,Error > + 'a { +Devres ::new (parent_dev,Self ::try_new (i2c_adapter, i2c_board_info)) + } + +fn try_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
Danilo Krummrich
reviewerRe: [PATCH v7 2/4] rust: i2c: add manual I2C device creation abstractions
rust/kernel/i2c.rs fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) { · line 382
Quoted 7 lines · Igor Korotin
rust/kernel/i2c.rs +7
-0+impl I2cAdapter { +/// Returns the I2C Adapter index. +#[inline] +pub fn get_nr (&self) ->i32 { +// SAFETY: `self.as_raw` is a valid pointer to a `struct i2c_adapter`. +unsafe { (*self.as_raw ()).nr } + }
Missing empty line. Also, please try to avoid the "get" prefix for functions / methods that do not increase a reference count. What about just index()?
Quoted 41 lines
rust/kernel/i2c.rs +41
-0+/// 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 () }) + } +} + +// 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.get_nr ()) }; + } + +unsafe fn dec_ref (obj:NonNull <Self >) { +// SAFETY: The safety requirements guarantee that the refcount is non-zero. +unsafe { bindings::i2c_put_adapter (obj.as_ref ().as_raw ()) } + } +} + +/// 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.
rust/kernel/i2c.rs fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) { · line 433
Quoted 10 lines
rust/kernel/i2c.rs +10
-0+#[inline(always)] +pub const fn new (type_: &'staticCStr , 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 () };
pin_init::zeroed()
Quoted 14 lines
rust/kernel/i2c.rs +14
-0+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 ) + } +}
PATCH v7 3/4 samples: rust: add Rust I2C sample driver
In reply to Igor KorotinAdd a new rust_driver_i2c sample, showing how to create a new i2c driver using ACPI/OF/Legacy ID tables.
--- MAINTAINERS | 1 + samples/rust/Kconfig | 11 ++++++ samples/rust/Makefile | 1 + samples/rust/rust_driver_i2c.rs | 69 +++++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+) create mode 100644 samples/rust/rust_driver_i2c.rs
MAINTAINERS +1 -0
@@ -11744,6 +11744,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
@@ -84,6 +84,17 @@ config SAMPLE_RUST_DEBUGFS_SCOPED 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
@@ -7,6 +7,7 @@ obj-$(CONFIG_SAMPLE_RUST_PRINT) += rust_print.o obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o 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_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_driver_i2c.rs new file +69 -0
69 lines not on this page · raw message
Signature · 1 line
2.43.0
Danilo Krummrich
reviewerRe: [PATCH v7 3/4] samples: rust: add Rust I2C sample driver
Quoted 6 lines · Igor Korotin
samples/rust/rust_driver_i2c.rs new file +0
-0
samples/rust/rust_driver_i2c.rs line 9
Quoted 9 lines
samples/rust/rust_driver_i2c.rs new file +9
-0@@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust I2C driver sample. + +use kernel::{acpi, c_str, device::Core , i2c, of, prelude::*, types::ARef }; + +struct SampleDriver { + _idev:ARef <i2c::I2cClient >, +}
Let's just leave the struct empty if idev isn't used anyways. :)
PATCH v7 4/4 samples: rust: add Rust I2C client registration sample
In reply to Igor KorotinAdd a new rust_i2c_client sample, showing how to create a new i2c client using i2c::Registration
--- samples/rust/Kconfig | 12 +++ samples/rust/Makefile | 1 + samples/rust/rust_i2c_client.rs | 142 ++++++++++++++++++++++++++++++++ 3 files changed, 155 insertions(+) create mode 100644 samples/rust/rust_i2c_client.rs
samples/rust/Kconfig +12 -0
@@ -95,6 +95,18 @@ config SAMPLE_RUST_DRIVER_I2C If unsure, say N. +config SAMPLE_RUST_I2C_CLIENT + tristate "Manual I2C Client" + depends on I2C && I2C_CHARDEV + help + This option builds the Rust I2C client manual creation + sample. + + To compile this as a module, choose M here: + the module will be called rust_i2c_client. + + If unsure, say N. + config SAMPLE_RUST_DRIVER_PCI tristate "PCI Driver" depends on PCI
samples/rust/Makefile +1 -0
@@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o 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_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_client.rs new file +142 -0
142 lines not on this page · raw message
Signature · 1 line
2.43.0
Danilo Krummrich
reviewerRe: [PATCH v7 4/4] samples: rust: add Rust I2C client registration sample
samples/rust/rust_i2c_client.rs line 107
Quoted 10 lines · Igor Korotin
samples/rust/rust_i2c_client.rs new file +10
-0+impl platform::Driver for SampleDriver { +type IdInfo = (); +const OF_ID_TABLE :Option <of::IdTable <Self ::IdInfo >> =Some (&OF_TABLE ); +const ACPI_ID_TABLE :Option <acpi::IdTable <Self ::IdInfo >> =Some (&ACPI_TABLE ); + +fn probe ( + pdev: &platform::Device <device::Core >, + _info:Option <&Self ::IdInfo >, + ) ->impl PinInit <Self ,Error > { + pin_init::pin_init_scope (move || {
We probably don't need pin_init_scope() here.
Quoted 16 lines
samples/rust/rust_i2c_client.rs new file +16
-0+dev_info! ( + pdev.as_ref (), +"Probe Rust I2C Client registration sample.\n" + ); + +Ok (kernel::try_pin_init!(Self { + parent_dev: pdev.into (), + + idev <- { +let adapter = i2c::I2cAdapter ::get (SAMPLE_I2C_ADAPTER_INDEX )?; + + i2c::Registration ::new (&adapter, &BOARD_INFO , pdev.as_ref ()) + } + })) + }) + }
samples/rust/rust_i2c_client.rs line 133
Quoted 10 lines
samples/rust/rust_i2c_client.rs new file +10
-0+} + +#[pinned_drop] +impl PinnedDrop for SampleDriver { +fn drop (self:Pin <&mut Self >) { +dev_info! ( + self.parent_dev.as_ref (), +"Remove Rust Platform driver for I2C Client registration sample.\n" + ); + }
Let's use unbind() here as well.
(Yes, the existing samples need to be updated. :)
Danilo Krummrich
reviewerQuoted 3 lines · Igor Korotin
v7:
- Rebase and updatei2c::Driver::probefunction based on patch series [1].
Can you please rebase onto driver-core-next from [1].
[1] https://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core.git/log/?h=driver-core-next
There are a few more nits I'd usually fix up on apply, but since you have to resend anyways, please find a few comments on the patches.