Skip to main content

kernel/
i2c.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! I2C Driver subsystem
4
5// I2C Driver abstractions.
6use crate::{
7    acpi,
8    container_of,
9    device,
10    device_id::{
11        RawDeviceId,
12        RawDeviceIdIndex, //
13    },
14    devres::Devres,
15    driver,
16    error::*,
17    of,
18    prelude::*,
19    sync::aref::{
20        ARef,
21        AlwaysRefCounted, //
22    },
23    types::Opaque, //
24};
25
26use core::{
27    marker::PhantomData,
28    mem::offset_of,
29    ptr::{
30        from_ref,
31        NonNull, //
32    }, //
33};
34
35/// An I2C device id table.
36#[repr(transparent)]
37#[derive(Clone, Copy)]
38pub struct DeviceId(bindings::i2c_device_id);
39
40impl DeviceId {
41    const I2C_NAME_SIZE: usize = 20;
42
43    /// Create a new device id from an I2C 'id' string.
44    #[inline(always)]
45    pub const fn new(id: &'static CStr) -> Self {
46        let src = id.to_bytes_with_nul();
47        build_assert!(src.len() <= Self::I2C_NAME_SIZE, "ID exceeds 20 bytes");
48        let mut i2c: bindings::i2c_device_id = pin_init::zeroed();
49        let mut i = 0;
50        while i < src.len() {
51            i2c.name[i] = src[i];
52            i += 1;
53        }
54
55        Self(i2c)
56    }
57}
58
59// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `i2c_device_id` and does not add
60// additional invariants, so it's safe to transmute to `RawType`.
61unsafe impl RawDeviceId for DeviceId {
62    type RawType = bindings::i2c_device_id;
63}
64
65// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
66unsafe impl RawDeviceIdIndex for DeviceId {
67    const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::i2c_device_id, driver_data);
68}
69
70/// IdTable type for I2C
71pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
72
73/// Create a I2C `IdTable` with its alias for modpost.
74#[macro_export]
75macro_rules! i2c_device_table {
76    ($($tt:tt)*) => {
77        $crate::module_device_table!("i2c", $crate::i2c::DeviceId, $($tt)*);
78    };
79}
80
81/// An adapter for the registration of I2C drivers.
82pub struct Adapter<T: Driver>(T);
83
84// SAFETY:
85// - `bindings::i2c_driver` is a C type declared as `repr(C)`.
86// - `T::Data` is the type of the driver's device private data.
87// - `struct i2c_driver` embeds a `struct device_driver`.
88// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
89unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
90    type DriverType = bindings::i2c_driver;
91    type DriverData<'bound> = T::Data<'bound>;
92    const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
93}
94
95// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
96// a preceding call to `register` has been successful.
97unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
98    unsafe fn register(
99        idrv: &Opaque<Self::DriverType>,
100        name: &'static CStr,
101        module: &'static ThisModule,
102    ) -> Result {
103        build_assert!(
104            T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(),
105            "At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver"
106        );
107
108        let i2c_table = match T::I2C_ID_TABLE {
109            Some(table) => table.as_ptr(),
110            None => core::ptr::null(),
111        };
112
113        let of_table = match T::OF_ID_TABLE {
114            Some(table) => table.as_ptr(),
115            None => core::ptr::null(),
116        };
117
118        let acpi_table = match T::ACPI_ID_TABLE {
119            Some(table) => table.as_ptr(),
120            None => core::ptr::null(),
121        };
122
123        // SAFETY: It's safe to set the fields of `struct i2c_client` on initialization.
124        unsafe {
125            (*idrv.get()).driver.name = name.as_char_ptr();
126            (*idrv.get()).probe = Some(Self::probe_callback);
127            (*idrv.get()).remove = Some(Self::remove_callback);
128            (*idrv.get()).shutdown = Some(Self::shutdown_callback);
129            (*idrv.get()).id_table = i2c_table;
130            (*idrv.get()).driver.of_match_table = of_table;
131            (*idrv.get()).driver.acpi_match_table = acpi_table;
132        }
133
134        // SAFETY: `idrv` is guaranteed to be a valid `DriverType`.
135        to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.get()) })
136    }
137
138    unsafe fn unregister(idrv: &Opaque<Self::DriverType>) {
139        // SAFETY: `idrv` is guaranteed to be a valid `DriverType`.
140        unsafe { bindings::i2c_del_driver(idrv.get()) }
141    }
142}
143
144impl<T: Driver> Adapter<T> {
145    extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_int {
146        // SAFETY: The I2C bus only ever calls the probe callback with a valid pointer to a
147        // `struct i2c_client`.
148        //
149        // INVARIANT: `idev` is valid for the duration of `probe_callback()`.
150        let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
151
152        let info = Self::i2c_id_info(idev).or_else(|| {
153            // SAFETY: `idev` matched data is of type `Self::IdInfo`.
154            unsafe { <Self as driver::Adapter>::id_info(idev.as_ref()) }
155        });
156
157        from_result(|| {
158            let data = T::probe(idev, info);
159
160            idev.as_ref().set_drvdata(data)?;
161            Ok(0)
162        })
163    }
164
165    extern "C" fn remove_callback(idev: *mut bindings::i2c_client) {
166        // SAFETY: `idev` is a valid pointer to a `struct i2c_client`.
167        let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
168
169        // SAFETY: `remove_callback` is only ever called after a successful call to
170        // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called
171        // and stored a `Pin<KBox<T::Data<'_>>>`.
172        let data = unsafe { idev.as_ref().drvdata_borrow::<T::Data<'_>>() };
173
174        T::unbind(idev, data);
175    }
176
177    extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) {
178        // SAFETY: `shutdown_callback` is only ever called for a valid `idev`
179        let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal<'_>>>() };
180
181        // SAFETY: `shutdown_callback` is only ever called after a successful call to
182        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
183        // and stored a `Pin<KBox<T::Data<'_>>>`.
184        let data = unsafe { idev.as_ref().drvdata_borrow::<T::Data<'_>>() };
185
186        T::shutdown(idev, data);
187    }
188
189    /// The [`i2c::IdTable`] of the corresponding driver.
190    fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter>::IdInfo>> {
191        T::I2C_ID_TABLE
192    }
193
194    /// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any.
195    ///
196    /// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`].
197    fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::IdInfo> {
198        let table = Self::i2c_id_table()?;
199
200        // SAFETY:
201        // - `table` has static lifetime, hence it's valid for reads
202        // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`.
203        let raw_id = unsafe { bindings::i2c_match_id(table.as_ptr(), dev.as_raw()) };
204
205        if raw_id.is_null() {
206            return None;
207        }
208
209        // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct i2c_device_id` and
210        // does not add additional invariants, so it's safe to transmute.
211        let id = unsafe { &*raw_id.cast::<DeviceId>() };
212
213        // SAFETY: `id` comes from `table` which is of type `IdArray<_, Self::IdInfo>`.
214        Some(unsafe { id.info_unchecked::<T::IdInfo>() })
215    }
216}
217
218impl<T: Driver> driver::Adapter for Adapter<T> {
219    type IdInfo = T::IdInfo;
220
221    fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
222        T::OF_ID_TABLE
223    }
224
225    fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
226        T::ACPI_ID_TABLE
227    }
228}
229
230/// Declares a kernel module that exposes a single i2c driver.
231///
232/// # Examples
233///
234/// ```ignore
235/// kernel::module_i2c_driver! {
236///     type: MyDriver,
237///     name: "Module name",
238///     authors: ["Author name"],
239///     description: "Description",
240///     license: "GPL v2",
241/// }
242/// ```
243#[macro_export]
244macro_rules! module_i2c_driver {
245    ($($f:tt)*) => {
246        $crate::module_driver!(<T>, $crate::i2c::Adapter<T>, { $($f)* });
247    };
248}
249
250/// The i2c driver trait.
251///
252/// Drivers must implement this trait in order to get a i2c driver registered.
253///
254/// # Example
255///
256///```
257/// # use kernel::{acpi, bindings, device::Core, i2c, of};
258///
259/// struct MyDriver;
260///
261/// kernel::acpi_device_table!(
262///     ACPI_TABLE,
263///     <MyDriver as i2c::Driver>::IdInfo,
264///     [
265///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
266///     ]
267/// );
268///
269/// kernel::i2c_device_table!(
270///     I2C_TABLE,
271///     <MyDriver as i2c::Driver>::IdInfo,
272///     [
273///          (i2c::DeviceId::new(c"rust_driver_i2c"), ())
274///     ]
275/// );
276///
277/// kernel::of_device_table!(
278///     OF_TABLE,
279///     <MyDriver as i2c::Driver>::IdInfo,
280///     [
281///         (of::DeviceId::new(c"test,device"), ())
282///     ]
283/// );
284///
285/// impl i2c::Driver for MyDriver {
286///     type IdInfo = ();
287///     type Data<'bound> = Self;
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<'bound>(
293///         _idev: &'bound i2c::I2cClient<Core<'_>>,
294///         _id_info: Option<&'bound Self::IdInfo>,
295///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
296///         Err(ENODEV)
297///     }
298///
299///     fn shutdown<'bound>(
300///         _idev: &'bound i2c::I2cClient<Core<'_>>,
301///         this: Pin<&Self::Data<'bound>>,
302///     ) {
303///     }
304/// }
305///```
306pub trait Driver {
307    /// The type holding information about each device id supported by the driver.
308    // TODO: Use `associated_type_defaults` once stabilized:
309    //
310    // ```
311    // type IdInfo: 'static = ();
312    // ```
313    type IdInfo: 'static;
314
315    /// The type of the driver's bus device private data.
316    type Data<'bound>: Send + 'bound;
317
318    /// The table of device ids supported by the driver.
319    const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = None;
320
321    /// The table of OF device ids supported by the driver.
322    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
323
324    /// The table of ACPI device ids supported by the driver.
325    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
326
327    /// I2C driver probe.
328    ///
329    /// Called when a new i2c client is added or discovered.
330    /// Implementers should attempt to initialize the client here.
331    fn probe<'bound>(
332        dev: &'bound I2cClient<device::Core<'_>>,
333        id_info: Option<&'bound Self::IdInfo>,
334    ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
335
336    /// I2C driver shutdown.
337    ///
338    /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the
339    /// [`I2cClient`] into a safe state. Implementing this callback is optional.
340    ///
341    /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware
342    /// to prevent undesired behavior during shutdown.
343    ///
344    /// This callback is distinct from final resource cleanup, as the driver instance remains valid
345    /// after it returns. Any deallocation or teardown of driver-owned resources should instead be
346    /// handled in `Drop`.
347    fn shutdown<'bound>(dev: &'bound I2cClient<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
348        let _ = (dev, this);
349    }
350
351    /// I2C driver unbind.
352    ///
353    /// Called when the [`I2cClient`] is unbound from its bound [`Driver`]. Implementing this
354    /// callback is optional.
355    ///
356    /// This callback serves as a place for drivers to perform teardown operations that require a
357    /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
358    /// operations to gracefully tear down the device.
359    ///
360    /// Otherwise, release operations for driver resources should be performed in `Drop`.
361    fn unbind<'bound>(dev: &'bound I2cClient<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
362        let _ = (dev, this);
363    }
364}
365
366/// The i2c adapter representation.
367///
368/// This structure represents the Rust abstraction for a C `struct i2c_adapter`. The
369/// implementation abstracts the usage of an existing C `struct i2c_adapter` that
370/// gets passed from the C side
371///
372/// # Invariants
373///
374/// A [`I2cAdapter`] instance represents a valid `struct i2c_adapter` created by the C portion of
375/// the kernel.
376#[repr(transparent)]
377pub struct I2cAdapter<Ctx: device::DeviceContext = device::Normal>(
378    Opaque<bindings::i2c_adapter>,
379    PhantomData<Ctx>,
380);
381
382impl<Ctx: device::DeviceContext> I2cAdapter<Ctx> {
383    fn as_raw(&self) -> *mut bindings::i2c_adapter {
384        self.0.get()
385    }
386}
387
388impl I2cAdapter {
389    /// Returns the I2C Adapter index.
390    #[inline]
391    pub fn index(&self) -> i32 {
392        // SAFETY: `self.as_raw` is a valid pointer to a `struct i2c_adapter`.
393        unsafe { (*self.as_raw()).nr }
394    }
395
396    /// Gets pointer to an `i2c_adapter` by index.
397    #[inline]
398    pub fn get(index: i32) -> Result<ARef<Self>> {
399        // SAFETY: `index` must refer to a valid I2C adapter; the kernel
400        // guarantees that `i2c_get_adapter(index)` returns either a valid
401        // pointer or NULL. `NonNull::new` guarantees the correct check.
402        let adapter = NonNull::new(unsafe { bindings::i2c_get_adapter(index) }).ok_or(ENODEV)?;
403
404        // SAFETY: `adapter` is non-null and points to a live `i2c_adapter`.
405        // `I2cAdapter` is #[repr(transparent)], so this cast is valid.
406        // `i2c_get_adapter` returned the adapter with an incremented refcount, which we pass to
407        // the `ARef`.
408        Ok(unsafe { ARef::from_raw(adapter.cast::<I2cAdapter<device::Normal>>()) })
409    }
410}
411
412// SAFETY: `I2cAdapter` is a transparent wrapper of a type that doesn't depend on
413// `I2cAdapter`'s generic argument.
414kernel::impl_device_context_deref!(unsafe { I2cAdapter });
415kernel::impl_device_context_into_aref!(I2cAdapter);
416
417// SAFETY: Instances of `I2cAdapter` are always reference-counted.
418unsafe impl AlwaysRefCounted for I2cAdapter {
419    #[inline]
420    fn inc_ref(&self) {
421        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
422        unsafe { bindings::i2c_get_adapter(self.index()) };
423    }
424
425    #[inline]
426    unsafe fn dec_ref(obj: NonNull<Self>) {
427        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
428        unsafe { bindings::i2c_put_adapter(obj.as_ref().as_raw()) }
429    }
430}
431
432/// The i2c board info representation
433///
434/// This structure represents the Rust abstraction for a C `struct i2c_board_info` structure,
435/// which is used for manual I2C client creation.
436#[repr(transparent)]
437pub struct I2cBoardInfo(bindings::i2c_board_info);
438
439impl I2cBoardInfo {
440    const I2C_TYPE_SIZE: usize = 20;
441    /// Create a new [`I2cBoardInfo`] for a kernel driver.
442    #[inline(always)]
443    pub const fn new(type_: &'static CStr, addr: u16) -> Self {
444        let src = type_.to_bytes_with_nul();
445        build_assert!(src.len() <= Self::I2C_TYPE_SIZE, "Type exceeds 20 bytes");
446        let mut i2c_board_info: bindings::i2c_board_info = pin_init::zeroed();
447        let mut i: usize = 0;
448        while i < src.len() {
449            i2c_board_info.type_[i] = src[i];
450            i += 1;
451        }
452
453        i2c_board_info.addr = addr;
454        Self(i2c_board_info)
455    }
456
457    fn as_raw(&self) -> *const bindings::i2c_board_info {
458        from_ref(&self.0)
459    }
460}
461
462/// The i2c client representation.
463///
464/// This structure represents the Rust abstraction for a C `struct i2c_client`. The
465/// implementation abstracts the usage of an existing C `struct i2c_client` that
466/// gets passed from the C side
467///
468/// # Invariants
469///
470/// A [`I2cClient`] instance represents a valid `struct i2c_client` created by the C portion of
471/// the kernel.
472#[repr(transparent)]
473pub struct I2cClient<Ctx: device::DeviceContext = device::Normal>(
474    Opaque<bindings::i2c_client>,
475    PhantomData<Ctx>,
476);
477
478impl<Ctx: device::DeviceContext> I2cClient<Ctx> {
479    fn as_raw(&self) -> *mut bindings::i2c_client {
480        self.0.get()
481    }
482}
483
484// SAFETY: `I2cClient` is a transparent wrapper of `struct i2c_client`.
485// The offset is guaranteed to point to a valid device field inside `I2cClient`.
486unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for I2cClient<Ctx> {
487    const OFFSET: usize = offset_of!(bindings::i2c_client, dev);
488}
489
490// SAFETY: `I2cClient` is a transparent wrapper of a type that doesn't depend on
491// `I2cClient`'s generic argument.
492kernel::impl_device_context_deref!(unsafe { I2cClient });
493kernel::impl_device_context_into_aref!(I2cClient);
494
495// SAFETY: Instances of `I2cClient` are always reference-counted.
496unsafe impl AlwaysRefCounted for I2cClient {
497    fn inc_ref(&self) {
498        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
499        unsafe { bindings::get_device(self.as_ref().as_raw()) };
500    }
501
502    unsafe fn dec_ref(obj: NonNull<Self>) {
503        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
504        unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) }
505    }
506}
507
508impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for I2cClient<Ctx> {
509    fn as_ref(&self) -> &device::Device<Ctx> {
510        let raw = self.as_raw();
511        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
512        // `struct i2c_client`.
513        let dev = unsafe { &raw mut (*raw).dev };
514
515        // SAFETY: `dev` points to a valid `struct device`.
516        unsafe { device::Device::from_raw(dev) }
517    }
518}
519
520impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &I2cClient<Ctx> {
521    type Error = kernel::error::Error;
522
523    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
524        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
525        // `struct device`.
526        if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } {
527            return Err(EINVAL);
528        }
529
530        // SAFETY: We've just verified that the type of `dev` equals to
531        // `bindings::i2c_client_type`, hence `dev` must be embedded in a valid
532        // `struct i2c_client` as guaranteed by the corresponding C code.
533        let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) };
534
535        // SAFETY: `idev` is a valid pointer to a `struct i2c_client`.
536        Ok(unsafe { &*idev.cast() })
537    }
538}
539
540// SAFETY: A `I2cClient` is always reference-counted and can be released from any thread.
541unsafe impl Send for I2cClient {}
542
543// SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient`
544// (i.e. `I2cClient<Normal>) are thread safe.
545unsafe impl Sync for I2cClient {}
546
547/// The registration of an i2c client device.
548///
549/// This type represents the registration of a [`struct i2c_client`]. When an instance of this
550/// type is dropped, its respective i2c client device will be unregistered from the system.
551///
552/// # Invariants
553///
554/// `self.0` always holds a valid pointer to an initialized and registered
555/// [`struct i2c_client`].
556#[repr(transparent)]
557pub struct Registration(NonNull<bindings::i2c_client>);
558
559impl Registration {
560    /// The C `i2c_new_client_device` function wrapper for manual I2C client creation.
561    pub fn new<'a>(
562        i2c_adapter: &I2cAdapter,
563        i2c_board_info: &I2cBoardInfo,
564        parent_dev: &'a device::Device<device::Bound>,
565    ) -> impl PinInit<Devres<Self>, Error> + 'a {
566        Devres::new(parent_dev, Self::try_new(i2c_adapter, i2c_board_info))
567    }
568
569    fn try_new(i2c_adapter: &I2cAdapter, i2c_board_info: &I2cBoardInfo) -> Result<Self> {
570        // SAFETY: the kernel guarantees that `i2c_new_client_device()` returns either a valid
571        // pointer or NULL. `from_err_ptr` separates errors. Following `NonNull::new`
572        // checks for NULL.
573        let raw_dev = from_err_ptr(unsafe {
574            bindings::i2c_new_client_device(i2c_adapter.as_raw(), i2c_board_info.as_raw())
575        })?;
576
577        let dev_ptr = NonNull::new(raw_dev).ok_or(ENODEV)?;
578
579        Ok(Self(dev_ptr))
580    }
581}
582
583impl Drop for Registration {
584    fn drop(&mut self) {
585        // SAFETY: `Drop` is only called for a valid `Registration`, which by invariant
586        // always contains a non-null pointer to an `i2c_client`.
587        unsafe { bindings::i2c_unregister_device(self.0.as_ptr()) }
588    }
589}
590
591// SAFETY: A `Registration` of a `struct i2c_client` can be released from any thread.
592unsafe impl Send for Registration {}
593
594// SAFETY: `Registration` offers no interior mutability (no mutation through &self
595// and no mutable access is exposed)
596unsafe impl Sync for Registration {}