kernel/platform.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! Abstractions for the platform bus.
4//!
5//! C header: [`include/linux/platform_device.h`](srctree/include/linux/platform_device.h)
6
7use crate::{
8 bindings, container_of, device, driver,
9 error::{to_result, Result},
10 of,
11 prelude::*,
12 str::CStr,
13 types::{ForeignOwnable, Opaque},
14 ThisModule,
15};
16
17use core::{
18 marker::PhantomData,
19 ptr::{addr_of_mut, NonNull},
20};
21
22/// An adapter for the registration of platform drivers.
23pub struct Adapter<T: Driver>(T);
24
25// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
26// a preceding call to `register` has been successful.
27unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
28 type RegType = bindings::platform_driver;
29
30 unsafe fn register(
31 pdrv: &Opaque<Self::RegType>,
32 name: &'static CStr,
33 module: &'static ThisModule,
34 ) -> Result {
35 let of_table = match T::OF_ID_TABLE {
36 Some(table) => table.as_ptr(),
37 None => core::ptr::null(),
38 };
39
40 // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
41 unsafe {
42 (*pdrv.get()).driver.name = name.as_char_ptr();
43 (*pdrv.get()).probe = Some(Self::probe_callback);
44 (*pdrv.get()).remove = Some(Self::remove_callback);
45 (*pdrv.get()).driver.of_match_table = of_table;
46 }
47
48 // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
49 to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
50 }
51
52 unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
53 // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
54 unsafe { bindings::platform_driver_unregister(pdrv.get()) };
55 }
56}
57
58impl<T: Driver + 'static> Adapter<T> {
59 extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
60 // SAFETY: The platform bus only ever calls the probe callback with a valid pointer to a
61 // `struct platform_device`.
62 //
63 // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
64 let pdev = unsafe { &*pdev.cast::<Device<device::Core>>() };
65
66 let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
67 match T::probe(pdev, info) {
68 Ok(data) => {
69 // Let the `struct platform_device` own a reference of the driver's private data.
70 // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
71 // `struct platform_device`.
72 unsafe {
73 bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign().cast())
74 };
75 }
76 Err(err) => return Error::to_errno(err),
77 }
78
79 0
80 }
81
82 extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
83 // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
84 let ptr = unsafe { bindings::platform_get_drvdata(pdev) }.cast();
85
86 // SAFETY: `remove_callback` is only ever called after a successful call to
87 // `probe_callback`, hence it's guaranteed that `ptr` points to a valid and initialized
88 // `KBox<T>` pointer created through `KBox::into_foreign`.
89 let _ = unsafe { KBox::<T>::from_foreign(ptr) };
90 }
91}
92
93impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
94 type IdInfo = T::IdInfo;
95
96 fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
97 T::OF_ID_TABLE
98 }
99}
100
101/// Declares a kernel module that exposes a single platform driver.
102///
103/// # Examples
104///
105/// ```ignore
106/// kernel::module_platform_driver! {
107/// type: MyDriver,
108/// name: "Module name",
109/// authors: ["Author name"],
110/// description: "Description",
111/// license: "GPL v2",
112/// }
113/// ```
114#[macro_export]
115macro_rules! module_platform_driver {
116 ($($f:tt)*) => {
117 $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
118 };
119}
120
121/// The platform driver trait.
122///
123/// Drivers must implement this trait in order to get a platform driver registered.
124///
125/// # Examples
126///
127///```
128/// # use kernel::{bindings, c_str, device::Core, of, platform};
129///
130/// struct MyDriver;
131///
132/// kernel::of_device_table!(
133/// OF_TABLE,
134/// MODULE_OF_TABLE,
135/// <MyDriver as platform::Driver>::IdInfo,
136/// [
137/// (of::DeviceId::new(c_str!("test,device")), ())
138/// ]
139/// );
140///
141/// impl platform::Driver for MyDriver {
142/// type IdInfo = ();
143/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
144///
145/// fn probe(
146/// _pdev: &platform::Device<Core>,
147/// _id_info: Option<&Self::IdInfo>,
148/// ) -> Result<Pin<KBox<Self>>> {
149/// Err(ENODEV)
150/// }
151/// }
152///```
153pub trait Driver: Send {
154 /// The type holding driver private data about each device id supported by the driver.
155 // TODO: Use associated_type_defaults once stabilized:
156 //
157 // ```
158 // type IdInfo: 'static = ();
159 // ```
160 type IdInfo: 'static;
161
162 /// The table of OF device ids supported by the driver.
163 const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>>;
164
165 /// Platform driver probe.
166 ///
167 /// Called when a new platform device is added or discovered.
168 /// Implementers should attempt to initialize the device here.
169 fn probe(dev: &Device<device::Core>, id_info: Option<&Self::IdInfo>)
170 -> Result<Pin<KBox<Self>>>;
171}
172
173/// The platform device representation.
174///
175/// This structure represents the Rust abstraction for a C `struct platform_device`. The
176/// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
177/// code that we get passed from the C side.
178///
179/// # Invariants
180///
181/// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
182/// the kernel.
183#[repr(transparent)]
184pub struct Device<Ctx: device::DeviceContext = device::Normal>(
185 Opaque<bindings::platform_device>,
186 PhantomData<Ctx>,
187);
188
189impl<Ctx: device::DeviceContext> Device<Ctx> {
190 fn as_raw(&self) -> *mut bindings::platform_device {
191 self.0.get()
192 }
193}
194
195// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
196// argument.
197kernel::impl_device_context_deref!(unsafe { Device });
198kernel::impl_device_context_into_aref!(Device);
199
200// SAFETY: Instances of `Device` are always reference-counted.
201unsafe impl crate::types::AlwaysRefCounted for Device {
202 fn inc_ref(&self) {
203 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
204 unsafe { bindings::get_device(self.as_ref().as_raw()) };
205 }
206
207 unsafe fn dec_ref(obj: NonNull<Self>) {
208 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
209 unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
210 }
211}
212
213impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
214 fn as_ref(&self) -> &device::Device<Ctx> {
215 // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
216 // `struct platform_device`.
217 let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
218
219 // SAFETY: `dev` points to a valid `struct device`.
220 unsafe { device::Device::as_ref(dev) }
221 }
222}
223
224impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
225 type Error = kernel::error::Error;
226
227 fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
228 // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
229 // `struct device`.
230 if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
231 return Err(EINVAL);
232 }
233
234 // SAFETY: We've just verified that the bus type of `dev` equals
235 // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
236 // `struct platform_device` as guaranteed by the corresponding C code.
237 let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
238
239 // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
240 Ok(unsafe { &*pdev.cast() })
241 }
242}
243
244// SAFETY: A `Device` is always reference-counted and can be released from any thread.
245unsafe impl Send for Device {}
246
247// SAFETY: `Device` can be shared among threads because all methods of `Device`
248// (i.e. `Device<Normal>) are thread safe.
249unsafe impl Sync for Device {}