From nobody Wed Oct 8 00:23:29 2025 Received: from mail-wr1-f50.google.com (mail-wr1-f50.google.com [209.85.221.50]) (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 E334125F973 for ; Sun, 5 Oct 2025 10:23:33 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.221.50 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759659816; cv=none; b=MJasncCzlK87b5QC8rwj+h4zYK82G9B0XZSL5Pu9/3fac8eKCoT+xJ6DCcKq+ssTj8INd7VLdrsAD86VOxo+OdsI5ppAK+TEB4Zor7KRaNi0UQUyhGvXqQ45K51VImzJnRCz8Z5++Df0q2q1CQaQDZVSm6yNkTxs2kMZV7nEbeE= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1759659816; c=relaxed/simple; bh=UMDssw2iXEw4kWMyKjYE4jsf/n85NqQORBti+lgd0js=; h=From:To:Cc:Subject:Date:Message-ID:In-Reply-To:References: MIME-Version:Content-Type; b=lqUdUYzKOApusOqXAkav6Dtvu3yp23nUoXbfot5/u9RGSnqBYcL/K48D7kaRwTNJ4awqxRrp/K4aJL8M0wtvkSQDC/Bm52geJE5O4AFP5+FKSYwyztsELwkxK+KDhrKqyYphYgyowy22T3zbybU3aNRc5Q7HmI0Y4XQd9juCjsw= 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=lqfiLBNW; arc=none smtp.client-ip=209.85.221.50 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="lqfiLBNW" Received: by mail-wr1-f50.google.com with SMTP id ffacd0b85a97d-421851bca51so2529741f8f.1 for ; Sun, 05 Oct 2025 03:23:33 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20230601; t=1759659812; x=1760264612; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to; bh=8zjpsAwvleb0S28WSHkKgjNunUX2sDDBza3LuuidDko=; b=lqfiLBNWriHxboyf4tWvdMj6UTNKsLB0/2NxUzVLcFp8K1QnLN3/sH2tGzYFKtViXJ 4p4KQdky6XET0M7XxbZcE7C/nMRYdRo6Gmy2RPKOwq3bAlnWLdY+QjPpgn7muBfiiDr5 unCPsxeq+s3a7QrbBMV1700lKJ1ygIP/M/v93y0DjEvm2CVunQW6tF8Up2l84iNsGUu9 WLFIfYT6qrvd8utVNlBaXNXQODSSGL8HF8w4kqG9tx23PfFXdZws99mw75wQ2UoITktD j7XFAYmOvhiLO1G1LiDel3wa9ygaPfI0GcdP+i1O9AUGHAcPi5cm8EuOFSTZRqiSd5mY 9nkA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20230601; t=1759659812; x=1760264612; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-message-state:from:to:cc :subject:date:message-id:reply-to; bh=8zjpsAwvleb0S28WSHkKgjNunUX2sDDBza3LuuidDko=; b=aCbukmh/NMXIJiuKEGkEga+6VJH2YBJJ9ht3bJ771LQ3tG4KKUejx/9UFh/Qh00ExD fFluxqFrUOFKMXdKvwCTaubssGWz2pd6SkoaBjb1Wo5dcW9gOmVq/V9q3T8JAuNDliMT 0mwsZ34hJx8BkBGMtBblG25UKeb9juHuPVzgxZG5+tPiy1jjvzRHRt6mmUo+gWorLJGZ 8D+ALO+aZTprxXG0IXG9RdmTS4G7/iCaNebBHqUNRm4Rw7dxzXhHvKgTDZwloQF2DW4S 768hNwn4AO7HTVKUUmtQ4cdUrARDCNGPXSVooHHw8pUQI3jgJ58amRpndrEuxTQINPN8 QTMg== X-Forwarded-Encrypted: i=1; AJvYcCW/F5Cr0fQF4Qveo8wNUJIa4k9sHYJdWitQYVDlptPIcJNNipNwrt6foh5idVg4NTLUniVSDO4RUt9TrdI=@vger.kernel.org X-Gm-Message-State: AOJu0YzKQoAkNYw6NuldGkGVWUrpLWHPLFCLxHCY8AgZe0R9lBS/ZqQh UCIa4JXNt1gQi5Y2Erle7WhySYU3AzGzCMFjJ/2p3ZvENa/uJDRfRGX0 X-Gm-Gg: ASbGncu8WsAWGcESMcr9lj2PH2Ea6MlQxoRug9e9QwiqCVSGa2gX7tdMwN8cdyfTixs v74Rs733ZB/cZZSJVPPj0kGmE+EVXrtzPnRfotdhoPAy0F+uLUs6D+QnqcGcmeZ+yrvIlNgYorZ lej48sEZHoFYPRVaSNcerhlX97S5Mx2TbG/45RRsUOusl/z/dRSNqnkMKTXO5ogCxY5csGKVmQC Zj3kvC5V1L4hrDkk1c/S5ohhsWPxBdrJpGhwF6V2mD//UWVq9EI550sZtYyV6NsK0oJquz8WgDP 8A6lZe8NeErF/P7fdDFfkrTp9XYwBKdSfKiJcJqHVCuM3iPbULDVsSOtyvs9qA+t4PrzCfbM7UG DNivd6r3zEEiuW64PnJQQR5PFNXVjmmvZaGvt6CZv7fDNCCIhLetzOJ1klJAuPHmSLKE= X-Google-Smtp-Source: AGHT+IF/LIK7j8Mg0aiNw4WPRoZmVZE1SOgvdXbXKJvrddweYTETJXKjwMOd2BsJmHTvPgGA7Th3GA== X-Received: by 2002:a05:6000:2086:b0:3ea:d9a7:43e4 with SMTP id ffacd0b85a97d-425671c1454mr6535931f8f.53.1759659812029; Sun, 05 Oct 2025 03:23:32 -0700 (PDT) Received: from Vasilio.Home ([2.127.51.206]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-4255d8a6c3esm15973804f8f.1.2025.10.05.03.23.31 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Sun, 05 Oct 2025 03:23:31 -0700 (PDT) From: Igor Korotin To: Miguel Ojeda , Alex Gaynor , Wolfram Sang Cc: Boqun Feng , 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 v6 1/3] rust: i2c: add basic I2C device and driver abstractions Date: Sun, 5 Oct 2025 11:23:28 +0100 Message-ID: <20251005102328.41899-1-igor.korotin.linux@gmail.com> X-Mailer: git-send-email 2.43.0 In-Reply-To: <20251005102226.41876-1-igor.korotin.linux@gmail.com> References: <20251005102226.41876-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 `prob= e` * `i2c::I2cClient` =E2=80=94 a safe wrapper around `struct i2c_client` * `i2c::Adapter` =E2=80=94 implements `driver::RegistrationOps` to hook int= o the generic `driver::Registration` machinery * `i2c::DeviceId` =E2=80=94 a `RawDeviceIdIndex` implementation for I2C dev= ice IDs Signed-off-by: Igor Korotin --- MAINTAINERS | 8 + rust/bindings/bindings_helper.h | 1 + rust/kernel/i2c.rs | 423 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 434 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..c5a8a5791523 --- /dev/null +++ b/rust/kernel/i2c.rs @@ -0,0 +1,423 @@ +// 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::{AlwaysRefCounted, 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 when re= gistering an i2c driver" + ); + + 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::>() }; + + // SAFETY: `shutdown_callback` is only ever called after a success= ful call to + // `probe_callback`, hence it's guaranteed that `Device::set_drvda= ta()` has been called + // and stored a `Pin>`. + let data =3D unsafe { idev.as_ref().drvdata_obtain::>>= () }; + + T::shutdown(idev, data.as_ref()); + } + + /// 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 `= dev.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, this: Pin<&Self>) { +/// } +/// } +///``` +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 by the kernel during system reboot or power-off to allow th= e [`Driver`] to bring the + /// [`Device`] into a safe state. Implementing this callback is option= al. + /// + /// Typical actions include stopping transfers, disabling interrupts, = or resetting the hardware + /// to prevent undesired behavior during shutdown. + /// + /// This callback is distinct from final resource cleanup, as the driv= er instance remains valid + /// after it returns. Any deallocation or teardown of driver-owned res= ources should instead be + /// handled in `Self::drop`. + fn shutdown(dev: &I2cClient, this: Pin<&Self>) { + let _ =3D (dev, this); + } + + /// I2C driver unbind. + /// + /// Called when a [`Device`] is unbound from its bound [`Driver`]. Imp= lementing this callback + /// is optional. + /// + /// This callback serves as a place for drivers to perform teardown op= erations that require a + /// `&Device` or `&Device` reference. For instance, drive= rs may try to perform I/O + /// operations to gracefully tear down the device. + /// + /// Otherwise, release operations for driver resources should be perfo= rmed in `Self::drop`. + fn unbind(dev: &I2cClient, this: Pin<&Self>) { + let _ =3D (dev, this); + } +} + +/// 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 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