From nobody Sat Oct 4 03:15:47 2025 Received: from mail-wr1-f45.google.com (mail-wr1-f45.google.com [209.85.221.45]) (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 3F8D536CE16; Wed, 20 Aug 2025 15:21:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.45 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703286; cv=none; b=bpxSKoOsWgJspK9T94dzK7wJ/vfAaBxIvQcdeQhLd8l/60b/wEAxyZQUOeIeujl5sQGLeQpUII+VofuM78I9jDtIaHtLuoSQ1lBs1eVj0jfNcLpuSK13nnUvTczAXnifz8R8pM7tTWFsuCA7zX/DUkqFJRX62CSOecWWc01NTZw= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703286; c=relaxed/simple; bh=xCkMSjzlQ7GgBBSwrdkKJLNLEgqmcccZVdAJlLU4BgA=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=LrrMf3Djx7Ane/ISsZenCsWkI8gupK28PvljPaRzpXJi0o9fg9E5FyEHsKgFrO8keCUFd9S28k53KLfsMXvWJxCNF6/p8DvRRYt3/8oPCxGXXlXXP+6F362Zu+gcGzDes8BsDmYmCRmi8uFwzOEge/RSyRIH7XUYKleiMnNMvHo= 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=kzmR83ym; arc=none smtp.client-ip=209.85.221.45 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="kzmR83ym" Received: by mail-wr1-f45.google.com with SMTP id ffacd0b85a97d-3b9d41d2a5cso15199f8f.0; Wed, 20 Aug 2025 08:21:23 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755703282; x=1756308082; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:from:to:cc:subject:date :message-id:reply-to; bh=yygWEAETBHG8SG46fjnMFvemyaEFLJ8GWxCVZxkDYLg=; b=kzmR83ymSFH9zzUyTBpKk+D90aGYghfYMajfqocvijR+4E8G+YQlngHNpWAbGjr0IG p7YvL0wREBS50ic/W38z/kcUsp9bMnHpTccgi/iK9AaMgAphS7QII2tbWNwYGEMhFp+i nlf44PIoIoZ/7bBhpsa+MeBmG7bNZkE4B8s453fkKU6Nl5yH/2ov+MyFSBIoi4PMAyq8 crsCGJcFBhhTVjjxNuuCfHzf5eGVOOJ9E6cPaD6rqbExGthBwJ8/iIGjVQJvCRAXe76T AspLOkfULCb1GqF+nICeQ9juRYNSIbaG2ptf4E8QidDhEKSWStC1vFN3Fz3ul3WusQqe bTSA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755703282; x=1756308082; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=yygWEAETBHG8SG46fjnMFvemyaEFLJ8GWxCVZxkDYLg=; b=td6lCg7vNfKRJIA+5ewOkOxN5krH24b035Mgvmzu+Wyo6mAONkl0qS+OKv4puV7bzF QBWuIbBYhdbRfR3gXPNkvWwuJZLGUHra051mf4jAAkJLBShK2MKgyZp1Xq5ComQ/vbWI Q6m4viSxzTI2f7+JOiqZpyYROrDRDyueks92MoFcYQjwazYiXIMH2ngOaJ/N1lThQ8C6 9t4CP+nqZLysxI6DXiAsj+aoX7nJArd8ek8KeGPjCfFzQd/LtjPELy6mZVS/7HViMp5Q zvPv/fG54QC1ZOaiF5SkPdInJY+k5sK1qOeiBH5UFXu+bew6hBNAzuM7e16cQ51a7EOL GOrQ== X-Forwarded-Encrypted: i=1; AJvYcCUi63rotfWA7Mj52bpB4rz2ONCV7ecGDIfUSbSjqBf0gWkjqxAgYM98jxR6cfiTALCJ+NIQb9jBBWE=@vger.kernel.org, AJvYcCVY1D+6dQBsWDD9h2jlqN2eCzqP6UtGWC1hchZ23Obnuzm/WGh4gBcaxoZlMo/L5plzxQ3apAG1C9VkBuDZzCM=@vger.kernel.org, AJvYcCXqMTY7sZKt9DjxSB5gUbEfDEPh3o9mOH8hs1vl04EEzm/ZwzrafinUtVCCf6CSuNttphQz3vvZXZC6q2UB@vger.kernel.org X-Gm-Message-State: AOJu0YzHQ+aTDQs3YKO3ZH7cdmt59J8x1cbkziY4Mfiq/J7w8ludl7pc TfadOj3DQy4+ACvcuq+3unjQYmOHas2Vi8djf1tbUOk2y5xyBp1ukAsQ X-Gm-Gg: ASbGncvf41gn1aUWaXUYB8l7w0IanzOiHxozNZp+H4sZOtg+sqLH5F2h3sA9MYN6xyX 51sUQoeKMD6egxJTRD2N+xyBuHtgUM9qCda/OSXRSzcPAJD9UoVOH9vYJU1Bw9yUBFEhezR2lKL N+tNAT4wacznLzBQNwPAxU1q9Lvm4Gv1BKGhqKTj7oUYOtiC6lJpDofauykbM7RuQBq1FlxtThm fdmegTt/1mnoxBylcQo3lGMr/9PR+ejy87HVphX6pXx3v17tn4CLxdbkRUN24aXleOiCfRwAdRL cjoUGz3CoUe3cTyp/R6p1vTnsf/6/IxoLiJynILIWVQQflMSOoR7wtJGH5+2/5rN7rnrnWoTm+s +w7vKdZsVeM3iaP9vCrCO1I6fYrkDxgM15izzKhj/n4iocsHlRxFAdSmdduZozYkRulG88dpG X-Google-Smtp-Source: AGHT+IFriWgpuiZa2QUfdFrDbMoSzYBtG3jhF5BtCP6qxN94+eVLwnHK2jaOPFKyf31IySegtD4Fvw== X-Received: by 2002:a05:6000:1a8b:b0:3b7:9bd2:7ad6 with SMTP id ffacd0b85a97d-3c32f943effmr2704445f8f.38.1755703281931; Wed, 20 Aug 2025 08:21:21 -0700 (PDT) Received: from igor-korotin-Precision-Tower-3620.airspan.com ([188.39.32.4]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3c4568499ecsm86724f8f.43.2025.08.20.08.21.20 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 20 Aug 2025 08:21:21 -0700 (PDT) Sender: Igor Korotin From: Igor Korotin To: Miguel Ojeda , Alex Gaynor , Wolfram Sang Cc: Boqun Feng , Daniel Almeida , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , Viresh Kumar , Asahi Lina , Wedson Almeida Filho , Alex Hung , Tamir Duberstein , Xiangfei Ding , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-i2c@vger.kernel.org Subject: [PATCH v4 1/3] rust: i2c: add basic I2C device and driver abstractions Date: Wed, 20 Aug 2025 16:19:13 +0100 Message-ID: <20250820151913.1814284-1-igor.korotin.linux@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250820151427.1812482-1-igor.korotin.linux@gmail.com> References: <20250820151427.1812482-1-igor.korotin.linux@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 the core abstractions needed for I2C drivers, including: - `i2c::Driver` =E2=80=94 the trait drivers must implement, including `pro= be` - `i2c::I2cClient` =E2=80=94 a safe wrapper around `struct i2c_client` - `i2c::Adapter` =E2=80=94 implements `driver::RegistrationOps` to hook in= to the generic `driver::Registration` machinery - `i2c::DeviceId` =E2=80=94 a `RawDeviceIdIndex` implementation for I2C device IDs Signed-off-by: Igor Korotin --- 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 diff --git a/MAINTAINERS b/MAINTAINERS index fe168477caa4..c44c7ac317b1 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11516,6 +11516,14 @@ F: include/linux/i2c.h F: include/uapi/linux/i2c-*.h F: include/uapi/linux/i2c.h =20 +I2C SUBSYSTEM [RUST] +M: Igor Korotin +R: Danilo Krummrich +R: Daniel Almeida +L: rust-for-linux@vger.kernel.org +S: Maintained +F: rust/kernel/i2c.rs + I2C SUBSYSTEM HOST DRIVERS M: Andi Shyti L: linux-i2c@vger.kernel.org diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 84d60635e8a9..81796d5e16e8 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -53,6 +53,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs new file mode 100644 index 000000000000..f5e8c4bc1b7d --- /dev/null +++ b/rust/kernel/i2c.rs @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! I2C Driver subsystem + +// I2C Driver abstractions. +use crate::{ + acpi, container_of, device, + device_id::{RawDeviceId, RawDeviceIdIndex}, + driver, + error::*, + of, + prelude::*, + types::Opaque, +}; + +use core::{marker::PhantomData, ptr::NonNull}; + +/// An I2C device id table. +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct DeviceId(bindings::i2c_device_id); + +impl DeviceId { + const I2C_NAME_SIZE: usize =3D 20; + + /// Create a new device id from an I2C 'id' string. + #[inline(always)] + pub const fn new(id: &'static CStr) -> Self { + build_assert!( + id.len_with_nul() <=3D Self::I2C_NAME_SIZE, + "ID exceeds 20 bytes" + ); + let src =3D id.as_bytes_with_nul(); + // Replace with `bindings::acpi_device_id::default()` once stabili= zed for `const`. + // SAFETY: FFI type is valid to be zero-initialized. + let mut i2c: bindings::i2c_device_id =3D unsafe { core::mem::zeroe= d() }; + let mut i =3D 0; + while i < src.len() { + i2c.name[i] =3D src[i]; + i +=3D 1; + } + + Self(i2c) + } +} + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `i2c_device_i= d` and does not add +// additional invariants, so it's safe to transmute to `RawType`. +unsafe impl RawDeviceId for DeviceId { + type RawType =3D bindings::i2c_device_id; +} + +// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. +unsafe impl RawDeviceIdIndex for DeviceId { + const DRIVER_DATA_OFFSET: usize =3D core::mem::offset_of!(bindings::i2= c_device_id, driver_data); + + fn index(&self) -> usize { + self.0.driver_data + } +} + +/// IdTable type for I2C +pub type IdTable =3D &'static dyn kernel::device_id::IdTable; + +/// Create a I2C `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! i2c_device_table { + ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $tabl= e_data: expr) =3D> { + const $table_name: $crate::device_id::IdArray< + $crate::i2c::DeviceId, + $id_info_type, + { $table_data.len() }, + > =3D $crate::device_id::IdArray::new($table_data); + + $crate::module_device_table!("i2c", $module_table_name, $table_nam= e); + }; +} + +/// An adapter for the registration of I2C drivers. +pub struct Adapter(T); + +// SAFETY: A call to `unregister` for a given instance of `RegType` is gua= ranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl driver::RegistrationOps for Adapter { + type RegType =3D bindings::i2c_driver; + + unsafe fn register( + idrv: &Opaque, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + build_assert!( + T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I= 2C_ID_TABLE.is_some(), + "At least one of ACPI/OF/Legacy tables must be present" + ); + + let i2c_table =3D match T::I2C_ID_TABLE { + Some(table) =3D> table.as_ptr(), + None =3D> core::ptr::null(), + }; + + let of_table =3D match T::OF_ID_TABLE { + Some(table) =3D> table.as_ptr(), + None =3D> core::ptr::null(), + }; + + let acpi_table =3D match T::ACPI_ID_TABLE { + Some(table) =3D> table.as_ptr(), + None =3D> core::ptr::null(), + }; + + // SAFETY: It's safe to set the fields of `struct i2c_client` on i= nitialization. + unsafe { + (*idrv.get()).driver.name =3D name.as_char_ptr(); + (*idrv.get()).probe =3D Some(Self::probe_callback); + (*idrv.get()).remove =3D Some(Self::remove_callback); + (*idrv.get()).shutdown =3D Some(Self::shutdown_callback); + (*idrv.get()).id_table =3D i2c_table; + (*idrv.get()).driver.of_match_table =3D of_table; + (*idrv.get()).driver.acpi_match_table =3D acpi_table; + } + + // SAFETY: `idrv` is guaranteed to be a valid `RegType`. + to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.ge= t()) }) + } + + unsafe fn unregister(idrv: &Opaque) { + // SAFETY: `idrv` is guaranteed to be a valid `RegType`. + unsafe { bindings::i2c_del_driver(idrv.get()) } + } +} + +impl Adapter { + extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kerne= l::ffi::c_int { + // SAFETY: The I2C bus only ever calls the probe callback with a v= alid pointer to a + // `struct i2c_client`. + // + // INVARIANT: `idev` is valid for the duration of `probe_callback(= )`. + let idev =3D unsafe { &*idev.cast::>() }; + + let info =3D + Self::i2c_id_info(idev).or_else(|| ::= id_info(idev.as_ref())); + + from_result(|| { + let data =3D T::probe(idev, info)?; + + idev.as_ref().set_drvdata(data); + Ok(0) + }) + } + + extern "C" fn remove_callback(idev: *mut bindings::i2c_client) { + // SAFETY: `idev` is a valid pointer to a `struct i2c_client`. + let idev =3D unsafe { &*idev.cast::>() }; + + // SAFETY: `remove_callback` is only ever called after a successfu= l call to + // `probe_callback`, hence it's guaranteed that `I2cClient::set_dr= vdata()` has been called + // and stored a `Pin>`. + drop(unsafe { idev.as_ref().drvdata_obtain::>>() }); + } + + extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) { + // SAFETY: `shutdown_callback` is only ever called for a valid `id= ev` + let idev =3D unsafe { &*idev.cast::>() }; + + T::shutdown(idev); + } + + /// The [`i2c::IdTable`] of the corresponding driver. + fn i2c_id_table() -> Option::IdInfo>= > { + T::I2C_ID_TABLE + } + + /// Returns the driver's private data from the matching entry in the [= `i2c::IdTable`], if any. + /// + /// If this returns `None`, it means there is no match with an entry i= n the [`i2c::IdTable`]. + fn i2c_id_info(dev: &I2cClient) -> Option<&'static ::IdInfo> { + let table =3D Self::i2c_id_table()?; + + // SAFETY: + // - `table` has static lifetime, hence it's valid for reads + // - `dev` is guaranteed to be valid while it's alive, and so is `= idev.as_raw()`. + let raw_id =3D unsafe { bindings::i2c_match_id(table.as_ptr(), dev= .as_raw()) }; + + if raw_id.is_null() { + return None; + } + + // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struc= t i2c_device_id` and + // does not add additional invariants, so it's safe to transmute. + let id =3D unsafe { &*raw_id.cast::() }; + + Some(table.info(::= index(id))) + } +} + +impl driver::Adapter for Adapter { + type IdInfo =3D T::IdInfo; + + fn of_id_table() -> Option> { + T::OF_ID_TABLE + } + + fn acpi_id_table() -> Option> { + T::ACPI_ID_TABLE + } +} + +/// Declares a kernel module that exposes a single i2c driver. +/// +/// # Examples +/// +/// ```ignore +/// kernel::module_i2c_driver! { +/// type: MyDriver, +/// name: "Module name", +/// authors: ["Author name"], +/// description: "Description", +/// license: "GPL v2", +/// } +/// ``` +#[macro_export] +macro_rules! module_i2c_driver { + ($($f:tt)*) =3D> { + $crate::module_driver!(, $crate::i2c::Adapter, { $($f)* }); + }; +} + +/// The i2c driver trait. +/// +/// Drivers must implement this trait in order to get a i2c driver registe= red. +/// +/// # Example +/// +///``` +/// # use kernel::{acpi, bindings, c_str, device::Core, i2c, of}; +/// +/// struct MyDriver; +/// +/// kernel::acpi_device_table!( +/// ACPI_TABLE, +/// MODULE_ACPI_TABLE, +/// ::IdInfo, +/// [ +/// (acpi::DeviceId::new(c_str!("LNUXBEEF")), ()) +/// ] +/// ); +/// +/// kernel::i2c_device_table!( +/// I2C_TABLE, +/// MODULE_I2C_TABLE, +/// ::IdInfo, +/// [ +/// (i2c::DeviceId::new(c_str!("rust_driver_i2c")), ()) +/// ] +/// ); +/// +/// kernel::of_device_table!( +/// OF_TABLE, +/// MODULE_OF_TABLE, +/// ::IdInfo, +/// [ +/// (of::DeviceId::new(c_str!("test,device")), ()) +/// ] +/// ); +/// +/// impl i2c::Driver for MyDriver { +/// type IdInfo =3D (); +/// const I2C_ID_TABLE: Option> =3D Some(&I= 2C_TABLE); +/// const OF_ID_TABLE: Option> =3D Some(&OF_= TABLE); +/// const ACPI_ID_TABLE: Option> =3D Some(= &ACPI_TABLE); +/// +/// fn probe( +/// _idev: &i2c::I2cClient, +/// _id_info: Option<&Self::IdInfo>, +/// ) -> Result>> { +/// Err(ENODEV) +/// } +/// +/// fn shutdown(_idev: &i2c::I2cClient) { +/// } +/// } +///``` +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 =3D (); + // ``` + type IdInfo: 'static; + + /// The table of device ids supported by the driver. + const I2C_ID_TABLE: Option> =3D None; + + /// The table of OF device ids supported by the driver. + const OF_ID_TABLE: Option> =3D None; + + /// The table of ACPI device ids supported by the driver. + const ACPI_ID_TABLE: Option> =3D None; + + /// I2C driver probe. + /// + /// Called when a new i2c client is added or discovered. + /// Implementers should attempt to initialize the client here. + fn probe( + dev: &I2cClient, + id_info: Option<&Self::IdInfo>, + ) -> Result>>; + + /// I2C driver shutdown + /// + /// Called when + fn shutdown(dev: &I2cClient) { + let _ =3D dev; + } +} + +/// The i2c client representation. +/// +/// This structure represents the Rust abstraction for a C `struct i2c_cli= ent`. The +/// implementation abstracts the usage of an existing C `struct i2c_client= ` that +/// gets passed from the C side +/// +/// # Invariants +/// +/// A [`I2cClient`] instance represents a valid `struct i2c_client` create= d by the C portion of +/// the kernel. +#[repr(transparent)] +pub struct I2cClient( + Opaque, + PhantomData, +); + +impl I2cClient { + fn as_raw(&self) -> *mut bindings::i2c_client { + self.0.get() + } +} + +// SAFETY: `I2cClient` is a transparent wrapper of a type that doesn't dep= end on `I2cClient`'s +// generic argument. +kernel::impl_device_context_deref!(unsafe { I2cClient }); +kernel::impl_device_context_into_aref!(I2cClient); + +// SAFETY: Instances of `I2cClient` are always reference-counted. +unsafe impl crate::types::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) } + } +} + +impl AsRef> for I2cClient<= Ctx> { + fn as_ref(&self) -> &device::Device { + let raw =3D self.as_raw(); + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a p= ointer to a valid + // `struct i2c_client`. + let dev =3D unsafe { &raw mut (*raw).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +impl TryFrom<&device::Device> for &I2cCli= ent { + type Error =3D kernel::error::Error; + + fn try_from(dev: &device::Device) -> Result { + // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a = valid pointer to a + // `struct device`. + if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } { + return Err(EINVAL); + } + + // SAFETY: We've just verified that the type of `dev` equals to + // `bindings::i2c_client_type`, hence `dev` must be embedded in a = valid + // `struct i2c_client` as guaranteed by the corresponding C code. + let idev =3D unsafe { container_of!(dev.as_raw(), bindings::i2c_cl= ient, dev) }; + + // SAFETY: `idev` is a valid pointer to a `struct i2c_client`. + Ok(unsafe { &*idev.cast() }) + } +} + +// SAFETY: A `I2cClient` is always reference-counted and can be released f= rom any thread. +unsafe impl Send for I2cClient {} + +// SAFETY: `I2cClient` can be shared among threads because all methods of = `I2cClient` +// (i.e. `I2cClient) are thread safe. +unsafe impl Sync for I2cClient {} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ed53169e795c..a5e97a9b1546 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -89,6 +89,8 @@ pub mod firmware; pub mod fmt; pub mod fs; +#[cfg(CONFIG_I2C =3D "y")] +pub mod i2c; pub mod init; pub mod io; pub mod ioctl; --=20 2.43.0 From nobody Sat Oct 4 03:15:47 2025 Received: from mail-wm1-f48.google.com (mail-wm1-f48.google.com [209.85.128.48]) (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 3F8CF2E8B83; Wed, 20 Aug 2025 15:23:43 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.48 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703426; cv=none; b=q4X7+WAtnGO5wQgIsg4etQk5wq+Y58U9aoOUzCf0637NWmIwuuRkdSHF813zrNBjBO3Ul6auAC5qqc/MjT/LVWfOf+PlErhy40dPTsP8HTmM2r8AGFZ7CzYCsue2QsJe+AXSdGm95pPYQg+zL+uU6SLJk0nTV9BfwYr65+zGZJI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703426; c=relaxed/simple; bh=LMU87ynpw1ytA3AunlRqXwnWF3lLOhrelFJ9C6WLnRU=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=fDJlFdja5KnOxnzowQ8RwRiYaMHkY/F29Ejau/VuBY0WaIRj7vdCJnk9j48SRWERrDumz0aII4OBAw85ZmDH9xhl6DzPfp6SFHnnANT4vm3dD2KafbTDVpEWCXY/0DybbKnwuvABgVUiFKGbbGHzy+eg60+D1K+TOEgxFjrvqIA= 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=heOZvz5v; arc=none smtp.client-ip=209.85.128.48 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="heOZvz5v" Received: by mail-wm1-f48.google.com with SMTP id 5b1f17b1804b1-45a1b0990b2so37996875e9.2; Wed, 20 Aug 2025 08:23:42 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755703421; x=1756308221; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:from:to:cc:subject:date :message-id:reply-to; bh=IWzhwdi0GvmaDa5hyGuSLLD9HdU8bxK8kWqGUA5Y6O8=; b=heOZvz5v+6BAixjTcroYMbkb/OGUSEXu6LlIt3aTEBHNvl4hNLf6/gSWzeSEG3nCdb b0kVzggYOYZKbs71voBENjPky3E9tYGcMG/69G9W1liBjMjldJKsp+CaS/ByzD9HH8Db LU4TzoW3GEXwS+VpVLFIxMdMCnRopYgo6PM8RG6L4lk/QyHfkQC5Ly/Fh5Nmj90hXmcR y6Aba2RWPetKtmvV3n6ieB/Ouca/FEyLMwgZYUAzMRO/1rTYIDaF/wUo4t25SDqKx1xp nVxSpNvjDqIY0W44AvUY14EQhb4fw2BT04zI8u347MeEHYcDu7tLrjCosCmi9gFxIaCw FizA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755703421; x=1756308221; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=IWzhwdi0GvmaDa5hyGuSLLD9HdU8bxK8kWqGUA5Y6O8=; b=RdDzhTS1zfY9HUfjKEWhgmRlR2vNqIpRzy8wTyJ1TfMAUAFM1YotG15/uPWq7Af11Y WcTVMZxmMjNkUwIDywXu0scChPLkJNSlBi2GZnqwzeCHgMzpqAShw//J12AAG4g+506w NhzLf31jJ7Tm4QisxAARPGSmhDNX0u+I/8vDcdm0dLxuD0UyiaPrwQI9zzxkqq/nLFBZ fUTYkTpyaEb18HhwhGuT4+Zqttmtcc+Mgg1xs5b28XxvXVPx1Qp/mMZmmG7BXaXIwz7W kHxYtm12BuD7HUpJnIlCAcQPRvyznRClj2Xjyzi45Jf3WDn06rLOo4ztE0VgO9oFDL5h 1caA== X-Forwarded-Encrypted: i=1; AJvYcCU/qiqxfJPwt/8Ri3X1XZP1+ZQsCTdGi5ETvDt8MbUZI80fKhVmCnxkkZCkNIGY3vTDMOhP7uC0J0//n/6e@vger.kernel.org, AJvYcCWPQxjVus+my5dcQrG597BiFagmHkrnR/EHlOsJxaHpSeRa7kSvMz/y3xxxBr2mlwr3VDxJEWEckLpzy1KQSx0=@vger.kernel.org, AJvYcCXKW1UxXX2BBRIQXTKi+VBvBHCxrounpFNHSLTvc5deNxOOC03ayT82Hp/UE4CpQ2X+c5wYpHQD+qM=@vger.kernel.org X-Gm-Message-State: AOJu0Yyr+7vuCV7uC9EjopdYUhK7ywFT5Zd8AuJCspREvg41qooDTd58 mfO6h8ZbYyepXX7T7RuaO4tiX0IBINRKTSzCGUHvnZ40Eoqsneiq8Quz X-Gm-Gg: ASbGncuRVp4xNga9vJ0N5VwpWHv8R3pDIEoM/+IW3b/Apq7rq31zYvzvqllJw2Lv7jP RqNLdQklAXbXxhU1SB89wJpgG9XQtTEbsIU9Xo0HHUyxs4XF0MF96P3FIn7u8oT6b1UUC+IIuNB g23a+m8/bZSzFC3bciINb9Pt3nyyHnBmbQYv3mpUgt1zJ0hS5Qx1JbRSwfzDIZ+psVuOEgE5i7Z XIYKk/nGTi7XIIRV9HILqAuYxEoT+Czg6JIG8NEhzVr+zR+xMQc0iA6Y/uorkjRD63jUzbBeUK/ EXrpi805S5qF/gXy9aD6fcNPG2tl+DzRngkHiPMmNr+QsnQ4syj/jU12It6kjXDjnftNi97tAvy hRRstMfi/5ClLilg5fIe6RtqAW5VGAWQ7PLU75xdBVHO//ooM6lPaL3iE13/7lEllxJH9IaUy X-Google-Smtp-Source: AGHT+IEttblMfinRS97uVSeUe82HJpCEBoNHucuP2iEtzsdfmgnTYkuMcAM1/iMppBMDqneoqfRpyA== X-Received: by 2002:a05:600c:3b83:b0:459:e165:2661 with SMTP id 5b1f17b1804b1-45b479f1120mr26440025e9.23.1755703421155; Wed, 20 Aug 2025 08:23:41 -0700 (PDT) Received: from igor-korotin-Precision-Tower-3620.airspan.com ([188.39.32.4]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-3c3c89cd4d4sm2061258f8f.42.2025.08.20.08.23.40 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 20 Aug 2025 08:23:40 -0700 (PDT) Sender: Igor Korotin From: Igor Korotin To: Miguel Ojeda , Alex Gaynor , Wolfram Sang Cc: Boqun Feng , Daniel Almeida , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , Viresh Kumar , Asahi Lina , Wedson Almeida Filho , Alex Hung , Tamir Duberstein , Xiangfei Ding , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-i2c@vger.kernel.org Subject: [PATCH v4 2/3] rust: i2c: add manual I2C device creation abstractions Date: Wed, 20 Aug 2025 16:21:38 +0100 Message-ID: <20250820152138.1814666-1-igor.korotin.linux@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250820151427.1812482-1-igor.korotin.linux@gmail.com> References: <20250820151427.1812482-1-igor.korotin.linux@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 In addition to the basic I2C device support, added 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` =E2=80=94 a NonNull pointer created by the function `i2c_new_client_device` * `i2c::I2cAdapter` =E2=80=94 a ref counted wrapper around `struct i2c_ada= pter` * `i2c::I2cBoardInfo` =E2=80=94 a safe wrapper around `struct i2c_board_in= fo` Signed-off-by: Igor Korotin --- rust/kernel/i2c.rs | 175 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 174 insertions(+), 1 deletion(-) diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index f5e8c4bc1b7d..851d20ec65b5 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -13,7 +13,10 @@ types::Opaque, }; =20 -use core::{marker::PhantomData, ptr::NonNull}; +use core::{ + marker::PhantomData, + ptr::{from_ref, NonNull}, +}; =20 /// An I2C device id table. #[repr(transparent)] @@ -316,6 +319,134 @@ fn shutdown(dev: &I2cClient) { } } =20 +/// The i2c adapter representation. +/// +/// This structure represents the Rust abstraction for a C `struct i2c_ada= pter`. The +/// implementation abstracts the usage of an existing C `struct i2c_adapte= r` that +/// gets passed from the C side +/// +/// # Invariants +/// +/// A [`I2cAdapter`] instance represents a valid `struct i2c_adapter` crea= ted by the C portion of +/// the kernel. +#[repr(transparent)] +pub struct I2cAdapter( + Opaque, + PhantomData, +); + +impl I2cAdapter { + fn as_raw(&self) -> *mut bindings::i2c_adapter { + self.0.get() + } + + /// Gets pointer to an `i2c_adapter` by index. + pub fn get(index: i32) -> Result<&'static 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 =3D NonNull::new(unsafe { bindings::i2c_get_adapter(in= dex) }).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.cast::().as_ref() }) + } +} + +impl Drop for I2cAdapter { + fn drop(&mut self) { + // SAFETY: This `I2cAdapter` was obtained from `i2c_get_adapter`, + // and calling `i2c_put_adapter` exactly once will correctly relea= se + // the reference count in the I2C core. It is safe to call from an= y context + unsafe { bindings::i2c_put_adapter(self.as_raw()) } + } +} + +// SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't de= pend 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::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) } + } +} + +impl AsRef> for I2cAdapter= { + fn as_ref(&self) -> &device::Device { + let raw =3D self.as_raw(); + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a p= ointer to a valid + // `struct i2c_adapter`. + let dev =3D unsafe { &raw mut (*raw).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +impl TryFrom<&device::Device> for &I2cAda= pter { + type Error =3D kernel::error::Error; + + fn try_from(dev: &device::Device) -> Result { + // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a = valid pointer to a + // `struct device`. + if unsafe { bindings::i2c_verify_adapter(dev.as_raw()).is_null() }= { + return Err(EINVAL); + } + + // SAFETY: We've just verified that the type of `dev` equals to + // `bindings::i2c_adapter_type`, hence `dev` must be embedded in a= valid + // `struct i2c_adapter` as guaranteed by the corresponding C code. + let idev =3D unsafe { container_of!(dev.as_raw(), bindings::i2c_ad= apter, dev) }; + + // SAFETY: `idev` is a valid pointer to a `struct i2c_adapter`. + Ok(unsafe { &*idev.cast() }) + } +} + +/// The i2c board info representation +/// +/// This structure represents the Rust abstraction for a C `struct i2c_boa= rd_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 =3D 20; + /// Create a new board=E2=80=90info for a kernel driver. + #[inline(always)] + pub const fn new(type_: &'static CStr, addr: u16) -> Self { + build_assert!( + type_.len_with_nul() <=3D Self::I2C_TYPE_SIZE, + "Type exceeds 20 bytes" + ); + let src =3D type_.as_bytes_with_nul(); + // Replace with `bindings::acpi_device_id::default()` once stabili= zed for `const`. + // SAFETY: FFI type is valid to be zero-initialized. + let mut i2c_board_info: bindings::i2c_board_info =3D unsafe { core= ::mem::zeroed() }; + let mut i: usize =3D 0; + while i < src.len() { + i2c_board_info.type_[i] =3D src[i]; + i +=3D 1; + } + + i2c_board_info.addr =3D 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_cli= ent`. The @@ -394,3 +525,45 @@ unsafe impl Send for I2cClient {} // SAFETY: `I2cClient` can be shared among threads because all methods of = `I2cClient` // (i.e. `I2cClient) 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); + +impl Registration { + /// The C `i2c_new_client_device` function wrapper for manual I2C clie= nt creation. + pub fn new(i2c_adapter: &I2cAdapter, i2c_board_info: &I2cBoardInfo) ->= Result { + // SAFETY: the kernel guarantees that `i2c_new_client_device()` re= turns either a valid + // pointer or NULL. `from_err_ptr` separates errors. Following `No= nNull::new` checks + // for NULL. + let raw_dev =3D from_err_ptr(unsafe { + bindings::i2c_new_client_device(i2c_adapter.as_raw(), i2c_boar= d_info.as_raw()) + })?; + + let dev_ptr =3D 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` does not expose any methods or fields that need = synchronization. +unsafe impl Sync for Registration {} --=20 2.43.0 From nobody Sat Oct 4 03:15:47 2025 Received: from mail-wm1-f41.google.com (mail-wm1-f41.google.com [209.85.128.41]) (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 71E0836CE00; Wed, 20 Aug 2025 15:25:52 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.41 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703554; cv=none; b=Qd56TQJwbExNG8CNVkQQvT3uktL1TR10ietB30cq+pz7SfXLnb5a6DHTzAYp+qneLTP25hI9Ci81LEPL0+mheWCFwpzGT7CtRlN/PQpkiT7R0aCxX2wIYNnIILqahDCCVIddPyd3HeIX/WBZOsKyeI49FF622GJjfoMkhgh9NO0= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1755703554; c=relaxed/simple; bh=IblGSvcl9YQ4J83zqi1Getk6bWaI1B1dN8cO0Jqw+lo=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version; b=iXLPwOfFO+syGNN2Yuyb15e6A7VKwFcek9kXOUd5Hbrb9JnyyZWKERh72Ok8qNyeX9nIjHPcfl9oj4gEDxrtq3xH7Xq+H2xjfruVxEnFxlcmhbTh5ZCD4eyB8K0Z7wPHf711ze1KQSqimzmTLzr22seB2WBsyP/5/NcSnoVAVZI= 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=S0rK9mkK; arc=none smtp.client-ip=209.85.128.41 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="S0rK9mkK" Received: by mail-wm1-f41.google.com with SMTP id 5b1f17b1804b1-45a1b05d252so48069835e9.1; Wed, 20 Aug 2025 08:25:52 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1755703551; x=1756308351; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:from:to:cc:subject:date :message-id:reply-to; bh=97f6BgM4JY/6DiuS5dYZ9XaNJjjXPDmqhV4WvduflVw=; b=S0rK9mkK3dMLryDAi9hrwesPsvTPt4wMiZSb29XFVXg72KDxAOuXIH2kPmAeZkWTZf qGraNikZc02xVz4z6D05Hm/kDj7CI3AhKRrThUlrlmpsupTWaEywcaQcXNsiP7fSEipJ oe2riemr4gvGfZ06NV6eyengu9W8VuiEDCMsnJ0NW2SjAY2rNLQLZ7KRW2EIIO6YJbA9 hFHaFSkkYUkCarvCJO8Ej0zx9DXJtiAt5yeJXrXkwpFhT86qkLJQO8MGUA1EPKKBt4ol zqqC6obNQBniDJe8jj5ToOiUmnloQaanT6RT4/OEtXGM6hHQ403cMn2OroWEpaHmqBIE n3jw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1755703551; x=1756308351; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:sender:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to; bh=97f6BgM4JY/6DiuS5dYZ9XaNJjjXPDmqhV4WvduflVw=; b=offCt1qGFjKjXCZOTn/Zo2zsudccNhW0dUOiDdfxCr+CpBbVoG1cxJS1RLb5jHIVmJ r5Ow+ixGsqIyr+JjweykSIY4Y1wOrvnp0vSRuh9MDH2t/MfhhivF/6zkg830z1leyV9J hWAPgDkzA9rVp/rK6o9k0vAkORaf2ejZsS3e1FGYF3irBjrazYuUiarHdI95j2u7Q0b5 ZhTEquKUHh9dfcBdTe4qr/tvkvA5IhwBXsO2G+J6ukwxNanzPxRaRRj1YGWWP2VdZkNk 6Gx9ArMysv9sK0NRAjI/2waH5q2GLTXE/U4xS4C1lIKFoUA/iJ26nKUK3nXobQdxXQs8 K4yQ== X-Forwarded-Encrypted: i=1; AJvYcCU0rVKVTzNpOtk+cANssfBtCeHnY0QLHMKAYRkHAiY61v48SnLZQeq2hHXiiKK0J8X4xFe6tQlm/QlZZnPt@vger.kernel.org, AJvYcCX8iA+QWw3TsoMaI6s0z/4hAggKSiIcFXA/EsCJD7MR+gWNqY5oH49dER6r5TMJYjA9u2cmymVt+PnlpWwEEIU=@vger.kernel.org, AJvYcCXP8u4B38CYdGmAyZ5pGChNoS9x3bbwwFpuP08ozvzG3J+hnBh09h4hqCH9Sb1hlQhxssP/fmoX9zg=@vger.kernel.org X-Gm-Message-State: AOJu0YxHZC7cRXXQxuQp9VBi6IgifPzmBFbGvfHb8AQRxmVVa+9ahFOC WdU7qDgivGMKPKsYRgAsfVrmtWLmdi7g+yLMTx1o6P2DbPe20OQ9VhmB X-Gm-Gg: ASbGncvAZbvKspDMZQ9xU2tpAvbn+Up1kbUT6FHb8W0uPz3nTd/1SAdXPsHYLPa8Ass QdhDtbK1+WSuQmbMsckSZRqJ9ojFHBVuiHu5ifLlrm2rYV1SKnpVJ2ncVyknY4R3UVS8qoTsD/1 B3B6e1BZ/qXNiuZocH3NeWI6xqBJSVwdRU9uoI+VO2SCiI1d0oc0qhZCQnkyKb1Tbf1jPlfAvoI kmr2Bb45h7LoMcr0hao+hXPAuYPy1P+z3pTrw9/sKxPF1Mc1RnuUlBUc9miANhdv/T8gn2aXmmx DgbQZ58tfFpq1Wxm1TwStvqGfoymlz9u1hkQzZXRmEImmpstUNhHj2BRQkI4NXw4L6IN/ExFZHM Sc5clWPY3tLdLYb9TyMAXLUC+CutPQ99/n97pC5s00oiRflHDZ6wrW7ebV/oRV5VZWzjL0kfs X-Google-Smtp-Source: AGHT+IHcCNOs3Z1q0Tuneuj4ew4hMEZEq7HovMkKEHGHdsnXVNyrHD2r+/oTFPsjC5xgBrn0dl4Mbw== X-Received: by 2002:a05:600c:4f51:b0:456:1c4a:82b2 with SMTP id 5b1f17b1804b1-45b4a4eb04fmr17635775e9.10.1755703550325; Wed, 20 Aug 2025 08:25:50 -0700 (PDT) Received: from igor-korotin-Precision-Tower-3620.airspan.com ([188.39.32.4]) by smtp.gmail.com with ESMTPSA id 5b1f17b1804b1-45b47cad57asm40709915e9.24.2025.08.20.08.25.49 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Wed, 20 Aug 2025 08:25:49 -0700 (PDT) Sender: Igor Korotin From: Igor Korotin To: Miguel Ojeda , Alex Gaynor , Wolfram Sang Cc: Boqun Feng , Daniel Almeida , Gary Guo , =?UTF-8?q?Bj=C3=B6rn=20Roy=20Baron?= , Benno Lossin , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , Viresh Kumar , Asahi Lina , Wedson Almeida Filho , Alex Hung , Tamir Duberstein , Xiangfei Ding , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-i2c@vger.kernel.org Subject: [PATCH v4 3/3] samples: rust: add Rust I2C sample driver Date: Wed, 20 Aug 2025 16:23:47 +0100 Message-ID: <20250820152347.1815097-1-igor.korotin.linux@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20250820151427.1812482-1-igor.korotin.linux@gmail.com> References: <20250820151427.1812482-1-igor.korotin.linux@gmail.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" 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. Signed-off-by: Igor Korotin --- 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 diff --git a/MAINTAINERS b/MAINTAINERS index c44c7ac317b1..2654a7ea0c80 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11523,6 +11523,7 @@ R: Daniel Almeida L: rust-for-linux@vger.kernel.org S: Maintained F: rust/kernel/i2c.rs +F: samples/rust/rust_driver_i2c.rs =20 I2C SUBSYSTEM HOST DRIVERS M: Andi Shyti diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 7f7371a004ee..28dae070b365 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -62,6 +62,17 @@ config SAMPLE_RUST_DMA =20 If unsure, say N. =20 +config SAMPLE_RUST_DRIVER_I2C + tristate "I2C Driver" + depends on I2C=3Dy + 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 diff --git a/samples/rust/Makefile b/samples/rust/Makefile index bd2faad63b4f..141d8f078248 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -5,6 +5,7 @@ obj-$(CONFIG_SAMPLE_RUST_MINIMAL) +=3D rust_minimal.o obj-$(CONFIG_SAMPLE_RUST_MISC_DEVICE) +=3D rust_misc_device.o obj-$(CONFIG_SAMPLE_RUST_PRINT) +=3D rust_print.o obj-$(CONFIG_SAMPLE_RUST_DMA) +=3D rust_dma.o +obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C) +=3D rust_driver_i2c.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) +=3D rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) +=3D rust_driver_platform.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) +=3D rust_driver_faux.o diff --git a/samples/rust/rust_driver_i2c.rs b/samples/rust/rust_driver_i2c= .rs new file mode 100644 index 000000000000..6dfc299d5aea --- /dev/null +++ b/samples/rust/rust_driver_i2c.rs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust I2C driver sample. +//! +//! This module shows how to: +//! +//! 1. Manually create an `i2c_client` at address `SAMPLE_I2C_CLIENT_ADDR` +//! on the adapter with index `SAMPLE_I2C_ADAPTER_INDEX`. +//! 2. Register a matching Rust-based I2C driver for that client. +//! +//! # Requirements +//! +//! - The target system must expose an I2C adapter at index +//! `SAMPLE_I2C_ADAPTER_INDEX`. +//! - To emulate an adapter for testing, you can load the +//! `i2c-stub` kernel module with an option `chip_addr` +//! For example for this sample driver to emulate an I2C device with +//! an address 0x30 you can use: +//! `modprobe i2c-stub chip_addr=3D0x30` +//! + +use kernel::{ + acpi, c_str, + device::{Core, Normal}, + i2c, of, + prelude::*, + types::ARef, +}; + +const SAMPLE_I2C_CLIENT_ADDR: u16 =3D 0x30; +const SAMPLE_I2C_ADAPTER_INDEX: i32 =3D 0; +const BOARD_INFO: i2c::I2cBoardInfo =3D + i2c::I2cBoardInfo::new(c_str!("rust_driver_i2c"), SAMPLE_I2C_CLIENT_AD= DR); + +struct SampleDriver { + pdev: ARef, +} + +kernel::acpi_device_table! { + ACPI_TABLE, + MODULE_ACPI_TABLE, + ::IdInfo, + [(acpi::DeviceId::new(c_str!("LNUXBEEF")), 0)] +} + +kernel::i2c_device_table! { + I2C_TABLE, + MODULE_I2C_TABLE, + ::IdInfo, + [(i2c::DeviceId::new(c_str!("rust_driver_i2c")), 0)] +} + +kernel::of_device_table! { + OF_TABLE, + MODULE_OF_TABLE, + ::IdInfo, + [(of::DeviceId::new(c_str!("test,rust_driver_i2c")), 0)] +} + +impl i2c::Driver for SampleDriver { + type IdInfo =3D u32; + + const ACPI_ID_TABLE: Option> =3D Some(&ACP= I_TABLE); + const I2C_ID_TABLE: Option> =3D Some(&I2C_T= ABLE); + const OF_ID_TABLE: Option> =3D Some(&OF_TABL= E); + + fn probe(pdev: &i2c::I2cClient, info: Option<&Self::IdInfo>) -> = Result>> { + let dev =3D pdev.as_ref(); + + dev_dbg!(dev, "Probe Rust I2C driver sample.\n"); + + if let Some(info) =3D info { + dev_info!(dev, "Probed with info: '{}'.\n", info); + } + + let drvdata =3D KBox::new(Self { pdev: pdev.into() }, GFP_KERNEL)?; + + Ok(drvdata.into()) + } + + fn shutdown(pdev: &i2c::I2cClient) { + dev_dbg!(pdev.as_ref(), "Shutdown Rust I2C driver sample.\n"); + } +} + +impl Drop for SampleDriver { + fn drop(&mut self) { + dev_dbg!(self.pdev.as_ref(), "Remove Rust I2C driver sample.\n"); + } +} + +// NOTE: The code below is expanded macro module_i2c_driver. It is not use= d 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 =3D kernel::i2c::Adapter; + +#[pin_data] +struct DriverModule { + #[pin] + _driver: kernel::driver::Registration>, + _reg: i2c::Registration, +} + +impl kernel::InPlaceModule for DriverModule { + fn init( + module: &'static kernel::ThisModule, + ) -> impl ::pin_init::PinInit { + kernel::try_pin_init!(Self { + _reg <- { + let adapter =3D i2c::I2cAdapter::::get(SAMPLE_I2C_= ADAPTER_INDEX)?; + + i2c::Registration::new(adapter, &BOARD_INFO) + }, + _driver <- kernel::driver::Registration::new( + ::NAME, module + ), + }) + } +} + +kernel::prelude::module! { + type: DriverModule, + name: "rust_driver_i2c", + authors: ["Igor Korotin"], + description: "Rust I2C driver", + license: "GPL v2", +} --=20 2.43.0