// SPDX-License-Identifier: GPL-2.012//! I2C Driver subsystem34// I2C Driver abstractions.5use crate::{6acpi,7container_of,8device,9device_id::{10RawDeviceId,11RawDeviceIdIndex, //12},13devres::Devres,14driver,15error::*,16of,17prelude::*,18types::{19AlwaysRefCounted,20Opaque, //21}, //22};2324use core::{25marker::PhantomData,26mem::offset_of,27ptr::{28from_ref,29NonNull, //30}, //31};3233use kernel::types::ARef;3435/// An I2C device id table.36#[repr(transparent)]37#[derive(Clone, Copy)]38pub struct DeviceId(bindings::i2c_device_id);3940impl DeviceId {41const I2C_NAME_SIZE: usize = 20;4243/// Create a new device id from an I2C 'id' string.44#[inline(always)]45pub const fn new(id: &'static CStr) -> Self {46let src = id.to_bytes_with_nul();47build_assert!(src.len() <= Self::I2C_NAME_SIZE, "ID exceeds 20 bytes");48let mut i2c: bindings::i2c_device_id = pin_init::zeroed();49let mut i = 0;50while i < src.len() {51i2c.name[i] = src[i];52i += 1;53}5455Self(i2c)56}57}5859// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `i2c_device_id` and does not add60// additional invariants, so it's safe to transmute to `RawType`.61unsafe impl RawDeviceId for DeviceId {62type RawType = bindings::i2c_device_id;63}6465// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.66unsafe impl RawDeviceIdIndex for DeviceId {67const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::i2c_device_id, driver_data);6869fn index(&self) -> usize {70self.0.driver_data71}72}7374/// IdTable type for I2C75pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;7677/// Create a I2C `IdTable` with its alias for modpost.78#[macro_export]79macro_rules! i2c_device_table {80($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {81const $table_name: $crate::device_id::IdArray<82$crate::i2c::DeviceId,83$id_info_type,84{ $table_data.len() },85> = $crate::device_id::IdArray::new($table_data);8687$crate::module_device_table!("i2c", $module_table_name, $table_name);88};89}9091/// An adapter for the registration of I2C drivers.92pub struct Adapter<T: Driver>(T);9394// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if95// a preceding call to `register` has been successful.96unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {97type RegType = bindings::i2c_driver;9899unsafe fn register(100idrv: &Opaque<Self::RegType>,101name: &'static CStr,102module: &'static ThisModule,103) -> Result {104build_assert!(105T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(),106"At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver"107);108109let i2c_table = match T::I2C_ID_TABLE {110Some(table) => table.as_ptr(),111None => core::ptr::null(),112};113114let of_table = match T::OF_ID_TABLE {115Some(table) => table.as_ptr(),116None => core::ptr::null(),117};118119let acpi_table = match T::ACPI_ID_TABLE {120Some(table) => table.as_ptr(),121None => core::ptr::null(),122};123124// SAFETY: It's safe to set the fields of `struct i2c_client` on initialization.125unsafe {126(*idrv.get()).driver.name = name.as_char_ptr();127(*idrv.get()).probe = Some(Self::probe_callback);128(*idrv.get()).remove = Some(Self::remove_callback);129(*idrv.get()).shutdown = Some(Self::shutdown_callback);130(*idrv.get()).id_table = i2c_table;131(*idrv.get()).driver.of_match_table = of_table;132(*idrv.get()).driver.acpi_match_table = acpi_table;133}134135// SAFETY: `idrv` is guaranteed to be a valid `RegType`.136to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.get()) })137}138139unsafe fn unregister(idrv: &Opaque<Self::RegType>) {140// SAFETY: `idrv` is guaranteed to be a valid `RegType`.141unsafe { bindings::i2c_del_driver(idrv.get()) }142}143}144145impl<T: Driver + 'static> Adapter<T> {146extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_int {147// SAFETY: The I2C bus only ever calls the probe callback with a valid pointer to a148// `struct i2c_client`.149//150// INVARIANT: `idev` is valid for the duration of `probe_callback()`.151let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };152153let info =154Self::i2c_id_info(idev).or_else(|| <Self as driver::Adapter>::id_info(idev.as_ref()));155156from_result(|| {157let data = T::probe(idev, info);158159idev.as_ref().set_drvdata(data)?;160Ok(0)161})162}163164extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {165// SAFETY: `idev` is a valid pointer to a `struct i2c_client`.166let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };167168// SAFETY: `remove_callback` is only ever called after a successful call to169// `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called170// and stored a `Pin<KBox<T>>`.171let data = unsafe { idev.as_ref().drvdata_obtain::<T>() };172173T::unbind(idev, data.as_ref());174}175176extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {177// SAFETY: `shutdown_callback` is only ever called for a valid `idev`178let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() };179180// SAFETY: `shutdown_callback` is only ever called after a successful call to181// `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called182// and stored a `Pin<KBox<T>>`.183let data = unsafe { idev.as_ref().drvdata_obtain::<T>() };184185T::shutdown(idev, data.as_ref());186}187188/// The [`i2c::IdTable`] of the corresponding driver.189fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter>::IdInfo>> {190T::I2C_ID_TABLE191}192193/// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any.194///195/// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`].196fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::IdInfo> {197let table = Self::i2c_id_table()?;198199// SAFETY:200// - `table` has static lifetime, hence it's valid for reads201// - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.202let raw_id = unsafe { bindings::i2c_match_id(table.as_ptr(), dev.as_raw()) };203204if raw_id.is_null() {205return None;206}207208// SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct i2c_device_id` and209// does not add additional invariants, so it's safe to transmute.210let id = unsafe { &*raw_id.cast::<DeviceId>() };211212Some(table.info(<DeviceId as RawDeviceIdIndex>::index(id)))213}214}215216impl<T: Driver + 'static> driver::Adapter for Adapter<T> {217type IdInfo = T::IdInfo;218219fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {220T::OF_ID_TABLE221}222223fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {224T::ACPI_ID_TABLE225}226}227228/// Declares a kernel module that exposes a single i2c driver.229///230/// # Examples231///232/// ```ignore233/// kernel::module_i2c_driver! {234/// type: MyDriver,235/// name: "Module name",236/// authors: ["Author name"],237/// description: "Description",238/// license: "GPL v2",239/// }240/// ```241#[macro_export]242macro_rules! module_i2c_driver {243($($f:tt)*) => {244$crate::module_driver!(<T>, $crate::i2c::Adapter<T>, { $($f)* });245};246}247248/// The i2c driver trait.249///250/// Drivers must implement this trait in order to get a i2c driver registered.251///252/// # Example253///254///```255/// # use kernel::{acpi, bindings, c_str, device::Core, i2c, of};256///257/// struct MyDriver;258///259/// kernel::acpi_device_table!(260/// ACPI_TABLE,261/// MODULE_ACPI_TABLE,262/// <MyDriver as i2c::Driver>::IdInfo,263/// [264/// (acpi::DeviceId::new(c_str!("LNUXBEEF")), ())265/// ]266/// );267///268/// kernel::i2c_device_table!(269/// I2C_TABLE,270/// MODULE_I2C_TABLE,271/// <MyDriver as i2c::Driver>::IdInfo,272/// [273/// (i2c::DeviceId::new(c_str!("rust_driver_i2c")), ())274/// ]275/// );276///277/// kernel::of_device_table!(278/// OF_TABLE,279/// MODULE_OF_TABLE,280/// <MyDriver as i2c::Driver>::IdInfo,281/// [282/// (of::DeviceId::new(c_str!("test,device")), ())283/// ]284/// );285///286/// impl i2c::Driver for MyDriver {287/// type IdInfo = ();288/// const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE);289/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);290/// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);291///292/// fn probe(293/// _idev: &i2c::I2cClient<Core>,294/// _id_info: Option<&Self::IdInfo>,295/// ) -> impl PinInit<Self, Error> {296/// Err(ENODEV)297/// }298///299/// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) {300/// }301/// }302///```303pub trait Driver: Send {304/// The type holding information about each device id supported by the driver.305// TODO: Use `associated_type_defaults` once stabilized:306//307// ```308// type IdInfo: 'static = ();309// ```310type IdInfo: 'static;311312/// The table of device ids supported by the driver.313const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = None;314315/// The table of OF device ids supported by the driver.316const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;317318/// The table of ACPI device ids supported by the driver.319const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;320321/// I2C driver probe.322///323/// Called when a new i2c client is added or discovered.324/// Implementers should attempt to initialize the client here.325fn probe(326dev: &I2cClient<device::Core>,327id_info: Option<&Self::IdInfo>,328) -> impl PinInit<Self, Error>;329330/// I2C driver shutdown.331///332/// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the333/// [`I2cClient`] into a safe state. Implementing this callback is optional.334///335/// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware336/// to prevent undesired behavior during shutdown.337///338/// This callback is distinct from final resource cleanup, as the driver instance remains valid339/// after it returns. Any deallocation or teardown of driver-owned resources should instead be340/// handled in `Self::drop`.341fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self>) {342let _ = (dev, this);343}344345/// I2C driver unbind.346///347/// Called when the [`I2cClient`] is unbound from its bound [`Driver`]. Implementing this348/// callback is optional.349///350/// This callback serves as a place for drivers to perform teardown operations that require a351/// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O352/// operations to gracefully tear down the device.353///354/// Otherwise, release operations for driver resources should be performed in `Self::drop`.355fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) {356let _ = (dev, this);357}358}359360/// The i2c adapter representation.361///362/// This structure represents the Rust abstraction for a C `struct i2c_adapter`. The363/// implementation abstracts the usage of an existing C `struct i2c_adapter` that364/// gets passed from the C side365///366/// # Invariants367///368/// A [`I2cAdapter`] instance represents a valid `struct i2c_adapter` created by the C portion of369/// the kernel.370#[repr(transparent)]371pub struct I2cAdapter<Ctx: device::DeviceContext = device::Normal>(372Opaque<bindings::i2c_adapter>,373PhantomData<Ctx>,374);375376impl<Ctx: device::DeviceContext> I2cAdapter<Ctx> {377fn as_raw(&self) -> *mut bindings::i2c_adapter {378self.0.get()379}380}381382impl I2cAdapter {383/// Returns the I2C Adapter index.384#[inline]385pub fn index(&self) -> i32 {386// SAFETY: `self.as_raw` is a valid pointer to a `struct i2c_adapter`.387unsafe { (*self.as_raw()).nr }388}389390/// Gets pointer to an `i2c_adapter` by index.391pub fn get(index: i32) -> Result<ARef<Self>> {392// SAFETY: `index` must refer to a valid I2C adapter; the kernel393// guarantees that `i2c_get_adapter(index)` returns either a valid394// pointer or NULL. `NonNull::new` guarantees the correct check.395let adapter = NonNull::new(unsafe { bindings::i2c_get_adapter(index) }).ok_or(ENODEV)?;396397// SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.398// `I2cAdapter` is #[repr(transparent)], so this cast is valid.399Ok(unsafe { (&*adapter.as_ptr().cast::<I2cAdapter<device::Normal>>()).into() })400}401}402403// SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't depend on404// `I2cAdapter`'s generic argument.405kernel::impl_device_context_deref!(unsafe { I2cAdapter });406kernel::impl_device_context_into_aref!(I2cAdapter);407408// SAFETY: Instances of `I2cAdapter` are always reference-counted.409unsafe impl crate::types::AlwaysRefCounted for I2cAdapter {410fn inc_ref(&self) {411// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.412unsafe { bindings::i2c_get_adapter(self.index()) };413}414415unsafe fn dec_ref(obj: NonNull<Self>) {416// SAFETY: The safety requirements guarantee that the refcount is non-zero.417unsafe { bindings::i2c_put_adapter(obj.as_ref().as_raw()) }418}419}420421/// The i2c board info representation422///423/// This structure represents the Rust abstraction for a C `struct i2c_board_info` structure,424/// which is used for manual I2C client creation.425#[repr(transparent)]426pub struct I2cBoardInfo(bindings::i2c_board_info);427428impl I2cBoardInfo {429const I2C_TYPE_SIZE: usize = 20;430/// Create a new [`I2cBoardInfo`] for a kernel driver.431#[inline(always)]432pub const fn new(type_: &'static CStr, addr: u16) -> Self {433let src = type_.to_bytes_with_nul();434build_assert!(src.len() <= Self::I2C_TYPE_SIZE, "Type exceeds 20 bytes");435let mut i2c_board_info: bindings::i2c_board_info = pin_init::zeroed();436let mut i: usize = 0;437while i < src.len() {438i2c_board_info.type_[i] = src[i];439i += 1;440}441442i2c_board_info.addr = addr;443Self(i2c_board_info)444}445446fn as_raw(&self) -> *const bindings::i2c_board_info {447from_ref(&self.0)448}449}450451/// The i2c client representation.452///453/// This structure represents the Rust abstraction for a C `struct i2c_client`. The454/// implementation abstracts the usage of an existing C `struct i2c_client` that455/// gets passed from the C side456///457/// # Invariants458///459/// A [`I2cClient`] instance represents a valid `struct i2c_client` created by the C portion of460/// the kernel.461#[repr(transparent)]462pub struct I2cClient<Ctx: device::DeviceContext = device::Normal>(463Opaque<bindings::i2c_client>,464PhantomData<Ctx>,465);466467impl<Ctx: device::DeviceContext> I2cClient<Ctx> {468fn as_raw(&self) -> *mut bindings::i2c_client {469self.0.get()470}471}472473// SAFETY: `I2cClient` is a transparent wrapper of `struct i2c_client`.474// The offset is guaranteed to point to a valid device field inside `I2cClient`.475unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<Ctx> {476const OFFSET: usize = offset_of!(bindings::i2c_client, dev);477}478479// SAFETY: `I2cClient` is a transparent wrapper of a type that doesn't depend on480// `I2cClient`'s generic argument.481kernel::impl_device_context_deref!(unsafe { I2cClient });482kernel::impl_device_context_into_aref!(I2cClient);483484// SAFETY: Instances of `I2cClient` are always reference-counted.485unsafe impl AlwaysRefCounted for I2cClient {486fn inc_ref(&self) {487// SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.488unsafe { bindings::get_device(self.as_ref().as_raw()) };489}490491unsafe fn dec_ref(obj: NonNull<Self>) {492// SAFETY: The safety requirements guarantee that the refcount is non-zero.493unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) }494}495}496497impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for I2cClient<Ctx> {498fn as_ref(&self) -> &device::Device<Ctx> {499let raw = self.as_raw();500// SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid501// `struct i2c_client`.502let dev = unsafe { &raw mut (*raw).dev };503504// SAFETY: `dev` points to a valid `struct device`.505unsafe { device::Device::from_raw(dev) }506}507}508509impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &I2cClient<Ctx> {510type Error = kernel::error::Error;511512fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {513// SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a514// `struct device`.515if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } {516return Err(EINVAL);517}518519// SAFETY: We've just verified that the type of `dev` equals to520// `bindings::i2c_client_type`, hence `dev` must be embedded in a valid521// `struct i2c_client` as guaranteed by the corresponding C code.522let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) };523524// SAFETY: `idev` is a valid pointer to a `struct i2c_client`.525Ok(unsafe { &*idev.cast() })526}527}528529// SAFETY: A `I2cClient` is always reference-counted and can be released from any thread.530unsafe impl Send for I2cClient {}531532// SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`533// (i.e. `I2cClient<Normal>) are thread safe.534unsafe impl Sync for I2cClient {}535536/// The registration of an i2c client device.537///538/// This type represents the registration of a [`struct i2c_client`]. When an instance of this539/// type is dropped, its respective i2c client device will be unregistered from the system.540///541/// # Invariants542///543/// `self.0` always holds a valid pointer to an initialized and registered544/// [`struct i2c_client`].545#[repr(transparent)]546pub struct Registration(NonNull<bindings::i2c_client>);547548impl Registration {549/// The C `i2c_new_client_device` function wrapper for manual I2C client creation.550pub fn new<'a>(551i2c_adapter: &I2cAdapter,552i2c_board_info: &I2cBoardInfo,553parent_dev: &'a device::Device<device::Bound>,554) -> impl PinInit<Devres<Self>, Error> + 'a {555Devres::new(parent_dev, Self::try_new(i2c_adapter, i2c_board_info))556}557558fn try_new(i2c_adapter: &I2cAdapter, i2c_board_info: &I2cBoardInfo) -> Result<Self> {559// SAFETY: the kernel guarantees that `i2c_new_client_device()` returns either a valid560// pointer or NULL. `from_err_ptr` separates errors. Following `NonNull::new`561// checks for NULL.562let raw_dev = from_err_ptr(unsafe {563bindings::i2c_new_client_device(i2c_adapter.as_raw(), i2c_board_info.as_raw())564})?;565566let dev_ptr = NonNull::new(raw_dev).ok_or(ENODEV)?;567568Ok(Self(dev_ptr))569}570}571572impl Drop for Registration {573fn drop(&mut self) {574// SAFETY: `Drop` is only called for a valid `Registration`, which by invariant575// always contains a non-null pointer to an `i2c_client`.576unsafe { bindings::i2c_unregister_device(self.0.as_ptr()) }577}578}579580// SAFETY: A `Registration` of a `struct i2c_client` can be released from any thread.581unsafe impl Send for Registration {}582583// SAFETY: `Registration` offers no interior mutability (no mutation through &self584// and no mutable access is exposed)585unsafe impl Sync for Registration {}586587588