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