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