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