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