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