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