Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

rust: i2c: add basic I2C device and driver abstractions

Implement the core abstractions needed for I2C drivers, including:

* `i2c::Driver` — the trait drivers must implement, including `probe`

* `i2c::I2cClient` — a safe wrapper around `struct i2c_client`

* `i2c::Adapter` — implements `driver::RegistrationOps` to hook into the
generic `driver::Registration` machinery

* `i2c::DeviceId` — a `RawDeviceIdIndex` implementation for I2C device IDs

Acked-by: Wolfram Sang <wsa+renesas@sang-engineering.com>
Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com>
Link: https://patch.msgid.link/20251116162144.171469-1-igor.korotin.linux@gmail.com
[ Remove unnecessary safety comment; fix rustdoc `Device` -> `I2cClient`.
- Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>

authored by

Igor Korotin and committed by
Danilo Krummrich
57c5bd9a dd6ff5cf

+445
+8
MAINTAINERS
··· 11743 11743 F: include/uapi/linux/i2c-*.h 11744 11744 F: include/uapi/linux/i2c.h 11745 11745 11746 + I2C SUBSYSTEM [RUST] 11747 + M: Igor Korotin <igor.korotin.linux@gmail.com> 11748 + R: Danilo Krummrich <dakr@kernel.org> 11749 + R: Daniel Almeida <daniel.almeida@collabora.com> 11750 + L: rust-for-linux@vger.kernel.org 11751 + S: Maintained 11752 + F: rust/kernel/i2c.rs 11753 + 11746 11754 I2C SUBSYSTEM HOST DRIVERS 11747 11755 M: Andi Shyti <andi.shyti@kernel.org> 11748 11756 L: linux-i2c@vger.kernel.org
+1
rust/bindings/bindings_helper.h
··· 58 58 #include <linux/firmware.h> 59 59 #include <linux/interrupt.h> 60 60 #include <linux/fs.h> 61 + #include <linux/i2c.h> 61 62 #include <linux/ioport.h> 62 63 #include <linux/jiffies.h> 63 64 #include <linux/jump_label.h>
+434
rust/kernel/i2c.rs
··· 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 + driver, 15 + error::*, 16 + of, 17 + prelude::*, 18 + types::{ 19 + AlwaysRefCounted, 20 + Opaque, // 21 + }, // 22 + }; 23 + 24 + use core::{ 25 + marker::PhantomData, 26 + ptr::NonNull, // 27 + }; 28 + 29 + /// An I2C device id table. 30 + #[repr(transparent)] 31 + #[derive(Clone, Copy)] 32 + pub struct DeviceId(bindings::i2c_device_id); 33 + 34 + impl DeviceId { 35 + const I2C_NAME_SIZE: usize = 20; 36 + 37 + /// Create a new device id from an I2C 'id' string. 38 + #[inline(always)] 39 + pub const fn new(id: &'static CStr) -> Self { 40 + build_assert!( 41 + id.len_with_nul() <= Self::I2C_NAME_SIZE, 42 + "ID exceeds 20 bytes" 43 + ); 44 + let src = id.as_bytes_with_nul(); 45 + let mut i2c: bindings::i2c_device_id = pin_init::zeroed(); 46 + let mut i = 0; 47 + while i < src.len() { 48 + i2c.name[i] = src[i]; 49 + i += 1; 50 + } 51 + 52 + Self(i2c) 53 + } 54 + } 55 + 56 + // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `i2c_device_id` and does not add 57 + // additional invariants, so it's safe to transmute to `RawType`. 58 + unsafe impl RawDeviceId for DeviceId { 59 + type RawType = bindings::i2c_device_id; 60 + } 61 + 62 + // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. 63 + unsafe impl RawDeviceIdIndex for DeviceId { 64 + const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::i2c_device_id, driver_data); 65 + 66 + fn index(&self) -> usize { 67 + self.0.driver_data 68 + } 69 + } 70 + 71 + /// IdTable type for I2C 72 + pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; 73 + 74 + /// Create a I2C `IdTable` with its alias for modpost. 75 + #[macro_export] 76 + macro_rules! i2c_device_table { 77 + ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => { 78 + const $table_name: $crate::device_id::IdArray< 79 + $crate::i2c::DeviceId, 80 + $id_info_type, 81 + { $table_data.len() }, 82 + > = $crate::device_id::IdArray::new($table_data); 83 + 84 + $crate::module_device_table!("i2c", $module_table_name, $table_name); 85 + }; 86 + } 87 + 88 + /// An adapter for the registration of I2C drivers. 89 + pub struct Adapter<T: Driver>(T); 90 + 91 + // SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if 92 + // a preceding call to `register` has been successful. 93 + unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> { 94 + type RegType = bindings::i2c_driver; 95 + 96 + unsafe fn register( 97 + idrv: &Opaque<Self::RegType>, 98 + name: &'static CStr, 99 + module: &'static ThisModule, 100 + ) -> Result { 101 + build_assert!( 102 + T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::I2C_ID_TABLE.is_some(), 103 + "At least one of ACPI/OF/Legacy tables must be present when registering an i2c driver" 104 + ); 105 + 106 + let i2c_table = match T::I2C_ID_TABLE { 107 + Some(table) => table.as_ptr(), 108 + None => core::ptr::null(), 109 + }; 110 + 111 + let of_table = match T::OF_ID_TABLE { 112 + Some(table) => table.as_ptr(), 113 + None => core::ptr::null(), 114 + }; 115 + 116 + let acpi_table = match T::ACPI_ID_TABLE { 117 + Some(table) => table.as_ptr(), 118 + None => core::ptr::null(), 119 + }; 120 + 121 + // SAFETY: It's safe to set the fields of `struct i2c_client` on initialization. 122 + unsafe { 123 + (*idrv.get()).driver.name = name.as_char_ptr(); 124 + (*idrv.get()).probe = Some(Self::probe_callback); 125 + (*idrv.get()).remove = Some(Self::remove_callback); 126 + (*idrv.get()).shutdown = Some(Self::shutdown_callback); 127 + (*idrv.get()).id_table = i2c_table; 128 + (*idrv.get()).driver.of_match_table = of_table; 129 + (*idrv.get()).driver.acpi_match_table = acpi_table; 130 + } 131 + 132 + // SAFETY: `idrv` is guaranteed to be a valid `RegType`. 133 + to_result(unsafe { bindings::i2c_register_driver(module.0, idrv.get()) }) 134 + } 135 + 136 + unsafe fn unregister(idrv: &Opaque<Self::RegType>) { 137 + // SAFETY: `idrv` is guaranteed to be a valid `RegType`. 138 + unsafe { bindings::i2c_del_driver(idrv.get()) } 139 + } 140 + } 141 + 142 + impl<T: Driver + 'static> Adapter<T> { 143 + extern "C" fn probe_callback(idev: *mut bindings::i2c_client) -> kernel::ffi::c_int { 144 + // SAFETY: The I2C bus only ever calls the probe callback with a valid pointer to a 145 + // `struct i2c_client`. 146 + // 147 + // INVARIANT: `idev` is valid for the duration of `probe_callback()`. 148 + let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() }; 149 + 150 + let info = 151 + Self::i2c_id_info(idev).or_else(|| <Self as driver::Adapter>::id_info(idev.as_ref())); 152 + 153 + from_result(|| { 154 + let data = T::probe(idev, info); 155 + 156 + idev.as_ref().set_drvdata(data)?; 157 + Ok(0) 158 + }) 159 + } 160 + 161 + extern "C" fn remove_callback(idev: *mut bindings::i2c_client) { 162 + // SAFETY: `idev` is a valid pointer to a `struct i2c_client`. 163 + let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() }; 164 + 165 + // SAFETY: `remove_callback` is only ever called after a successful call to 166 + // `probe_callback`, hence it's guaranteed that `I2cClient::set_drvdata()` has been called 167 + // and stored a `Pin<KBox<T>>`. 168 + let data = unsafe { idev.as_ref().drvdata_obtain::<T>() }; 169 + 170 + T::unbind(idev, data.as_ref()); 171 + } 172 + 173 + extern "C" fn shutdown_callback(idev: *mut bindings::i2c_client) { 174 + // SAFETY: `shutdown_callback` is only ever called for a valid `idev` 175 + let idev = unsafe { &*idev.cast::<I2cClient<device::CoreInternal>>() }; 176 + 177 + // SAFETY: `shutdown_callback` is only ever called after a successful call to 178 + // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called 179 + // and stored a `Pin<KBox<T>>`. 180 + let data = unsafe { idev.as_ref().drvdata_obtain::<T>() }; 181 + 182 + T::shutdown(idev, data.as_ref()); 183 + } 184 + 185 + /// The [`i2c::IdTable`] of the corresponding driver. 186 + fn i2c_id_table() -> Option<IdTable<<Self as driver::Adapter>::IdInfo>> { 187 + T::I2C_ID_TABLE 188 + } 189 + 190 + /// Returns the driver's private data from the matching entry in the [`i2c::IdTable`], if any. 191 + /// 192 + /// If this returns `None`, it means there is no match with an entry in the [`i2c::IdTable`]. 193 + fn i2c_id_info(dev: &I2cClient) -> Option<&'static <Self as driver::Adapter>::IdInfo> { 194 + let table = Self::i2c_id_table()?; 195 + 196 + // SAFETY: 197 + // - `table` has static lifetime, hence it's valid for reads 198 + // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`. 199 + let raw_id = unsafe { bindings::i2c_match_id(table.as_ptr(), dev.as_raw()) }; 200 + 201 + if raw_id.is_null() { 202 + return None; 203 + } 204 + 205 + // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct i2c_device_id` and 206 + // does not add additional invariants, so it's safe to transmute. 207 + let id = unsafe { &*raw_id.cast::<DeviceId>() }; 208 + 209 + Some(table.info(<DeviceId as RawDeviceIdIndex>::index(id))) 210 + } 211 + } 212 + 213 + impl<T: Driver + 'static> driver::Adapter for Adapter<T> { 214 + type IdInfo = T::IdInfo; 215 + 216 + fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> { 217 + T::OF_ID_TABLE 218 + } 219 + 220 + fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> { 221 + T::ACPI_ID_TABLE 222 + } 223 + } 224 + 225 + /// Declares a kernel module that exposes a single i2c driver. 226 + /// 227 + /// # Examples 228 + /// 229 + /// ```ignore 230 + /// kernel::module_i2c_driver! { 231 + /// type: MyDriver, 232 + /// name: "Module name", 233 + /// authors: ["Author name"], 234 + /// description: "Description", 235 + /// license: "GPL v2", 236 + /// } 237 + /// ``` 238 + #[macro_export] 239 + macro_rules! module_i2c_driver { 240 + ($($f:tt)*) => { 241 + $crate::module_driver!(<T>, $crate::i2c::Adapter<T>, { $($f)* }); 242 + }; 243 + } 244 + 245 + /// The i2c driver trait. 246 + /// 247 + /// Drivers must implement this trait in order to get a i2c driver registered. 248 + /// 249 + /// # Example 250 + /// 251 + ///``` 252 + /// # use kernel::{acpi, bindings, c_str, device::Core, i2c, of}; 253 + /// 254 + /// struct MyDriver; 255 + /// 256 + /// kernel::acpi_device_table!( 257 + /// ACPI_TABLE, 258 + /// MODULE_ACPI_TABLE, 259 + /// <MyDriver as i2c::Driver>::IdInfo, 260 + /// [ 261 + /// (acpi::DeviceId::new(c_str!("LNUXBEEF")), ()) 262 + /// ] 263 + /// ); 264 + /// 265 + /// kernel::i2c_device_table!( 266 + /// I2C_TABLE, 267 + /// MODULE_I2C_TABLE, 268 + /// <MyDriver as i2c::Driver>::IdInfo, 269 + /// [ 270 + /// (i2c::DeviceId::new(c_str!("rust_driver_i2c")), ()) 271 + /// ] 272 + /// ); 273 + /// 274 + /// kernel::of_device_table!( 275 + /// OF_TABLE, 276 + /// MODULE_OF_TABLE, 277 + /// <MyDriver as i2c::Driver>::IdInfo, 278 + /// [ 279 + /// (of::DeviceId::new(c_str!("test,device")), ()) 280 + /// ] 281 + /// ); 282 + /// 283 + /// impl i2c::Driver for MyDriver { 284 + /// type IdInfo = (); 285 + /// const I2C_ID_TABLE: Option<i2c::IdTable<Self::IdInfo>> = Some(&I2C_TABLE); 286 + /// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); 287 + /// const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE); 288 + /// 289 + /// fn probe( 290 + /// _idev: &i2c::I2cClient<Core>, 291 + /// _id_info: Option<&Self::IdInfo>, 292 + /// ) -> impl PinInit<Self, Error> { 293 + /// Err(ENODEV) 294 + /// } 295 + /// 296 + /// fn shutdown(_idev: &i2c::I2cClient<Core>, this: Pin<&Self>) { 297 + /// } 298 + /// } 299 + ///``` 300 + pub trait Driver: Send { 301 + /// The type holding information about each device id supported by the driver. 302 + // TODO: Use `associated_type_defaults` once stabilized: 303 + // 304 + // ``` 305 + // type IdInfo: 'static = (); 306 + // ``` 307 + type IdInfo: 'static; 308 + 309 + /// The table of device ids supported by the driver. 310 + const I2C_ID_TABLE: Option<IdTable<Self::IdInfo>> = None; 311 + 312 + /// The table of OF device ids supported by the driver. 313 + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; 314 + 315 + /// The table of ACPI device ids supported by the driver. 316 + const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None; 317 + 318 + /// I2C driver probe. 319 + /// 320 + /// Called when a new i2c client is added or discovered. 321 + /// Implementers should attempt to initialize the client here. 322 + fn probe( 323 + dev: &I2cClient<device::Core>, 324 + id_info: Option<&Self::IdInfo>, 325 + ) -> impl PinInit<Self, Error>; 326 + 327 + /// I2C driver shutdown. 328 + /// 329 + /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the 330 + /// [`I2cClient`] into a safe state. Implementing this callback is optional. 331 + /// 332 + /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware 333 + /// to prevent undesired behavior during shutdown. 334 + /// 335 + /// This callback is distinct from final resource cleanup, as the driver instance remains valid 336 + /// after it returns. Any deallocation or teardown of driver-owned resources should instead be 337 + /// handled in `Self::drop`. 338 + fn shutdown(dev: &I2cClient<device::Core>, this: Pin<&Self>) { 339 + let _ = (dev, this); 340 + } 341 + 342 + /// I2C driver unbind. 343 + /// 344 + /// Called when the [`I2cClient`] is unbound from its bound [`Driver`]. Implementing this 345 + /// callback is optional. 346 + /// 347 + /// This callback serves as a place for drivers to perform teardown operations that require a 348 + /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O 349 + /// operations to gracefully tear down the device. 350 + /// 351 + /// Otherwise, release operations for driver resources should be performed in `Self::drop`. 352 + fn unbind(dev: &I2cClient<device::Core>, this: Pin<&Self>) { 353 + let _ = (dev, this); 354 + } 355 + } 356 + 357 + /// The i2c client representation. 358 + /// 359 + /// This structure represents the Rust abstraction for a C `struct i2c_client`. The 360 + /// implementation abstracts the usage of an existing C `struct i2c_client` that 361 + /// gets passed from the C side 362 + /// 363 + /// # Invariants 364 + /// 365 + /// A [`I2cClient`] instance represents a valid `struct i2c_client` created by the C portion of 366 + /// the kernel. 367 + #[repr(transparent)] 368 + pub struct I2cClient<Ctx: device::DeviceContext = device::Normal>( 369 + Opaque<bindings::i2c_client>, 370 + PhantomData<Ctx>, 371 + ); 372 + 373 + impl<Ctx: device::DeviceContext> I2cClient<Ctx> { 374 + fn as_raw(&self) -> *mut bindings::i2c_client { 375 + self.0.get() 376 + } 377 + } 378 + 379 + // SAFETY: `I2cClient` is a transparent wrapper of a type that doesn't depend on 380 + // `I2cClient`'s generic argument. 381 + kernel::impl_device_context_deref!(unsafe { I2cClient }); 382 + kernel::impl_device_context_into_aref!(I2cClient); 383 + 384 + // SAFETY: Instances of `I2cClient` are always reference-counted. 385 + unsafe impl AlwaysRefCounted for I2cClient { 386 + fn inc_ref(&self) { 387 + // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 388 + unsafe { bindings::get_device(self.as_ref().as_raw()) }; 389 + } 390 + 391 + unsafe fn dec_ref(obj: NonNull<Self>) { 392 + // SAFETY: The safety requirements guarantee that the refcount is non-zero. 393 + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) } 394 + } 395 + } 396 + 397 + impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for I2cClient<Ctx> { 398 + fn as_ref(&self) -> &device::Device<Ctx> { 399 + let raw = self.as_raw(); 400 + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid 401 + // `struct i2c_client`. 402 + let dev = unsafe { &raw mut (*raw).dev }; 403 + 404 + // SAFETY: `dev` points to a valid `struct device`. 405 + unsafe { device::Device::from_raw(dev) } 406 + } 407 + } 408 + 409 + impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &I2cClient<Ctx> { 410 + type Error = kernel::error::Error; 411 + 412 + fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> { 413 + // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a 414 + // `struct device`. 415 + if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } { 416 + return Err(EINVAL); 417 + } 418 + 419 + // SAFETY: We've just verified that the type of `dev` equals to 420 + // `bindings::i2c_client_type`, hence `dev` must be embedded in a valid 421 + // `struct i2c_client` as guaranteed by the corresponding C code. 422 + let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) }; 423 + 424 + // SAFETY: `idev` is a valid pointer to a `struct i2c_client`. 425 + Ok(unsafe { &*idev.cast() }) 426 + } 427 + } 428 + 429 + // SAFETY: A `I2cClient` is always reference-counted and can be released from any thread. 430 + unsafe impl Send for I2cClient {} 431 + 432 + // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient` 433 + // (i.e. `I2cClient<Normal>) are thread safe. 434 + unsafe impl Sync for I2cClient {}
+2
rust/kernel/lib.rs
··· 94 94 pub mod firmware; 95 95 pub mod fmt; 96 96 pub mod fs; 97 + #[cfg(CONFIG_I2C = "y")] 98 + pub mod i2c; 97 99 pub mod id_pool; 98 100 pub mod init; 99 101 pub mod io;