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::{ARef, ForeignOwnable, Opaque},
14    ThisModule,
15};
16
17use core::ptr::addr_of_mut;
18
19/// An adapter for the registration of platform drivers.
20pub struct Adapter<T: Driver>(T);
21
22// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
23// a preceding call to `register` has been successful.
24unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
25    type RegType = bindings::platform_driver;
26
27    unsafe fn register(
28        pdrv: &Opaque<Self::RegType>,
29        name: &'static CStr,
30        module: &'static ThisModule,
31    ) -> Result {
32        let of_table = match T::OF_ID_TABLE {
33            Some(table) => table.as_ptr(),
34            None => core::ptr::null(),
35        };
36
37        // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
38        unsafe {
39            (*pdrv.get()).driver.name = name.as_char_ptr();
40            (*pdrv.get()).probe = Some(Self::probe_callback);
41            (*pdrv.get()).remove = Some(Self::remove_callback);
42            (*pdrv.get()).driver.of_match_table = of_table;
43        }
44
45        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
46        to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
47    }
48
49    unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
50        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
51        unsafe { bindings::platform_driver_unregister(pdrv.get()) };
52    }
53}
54
55impl<T: Driver + 'static> Adapter<T> {
56    extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
57        // SAFETY: The platform bus only ever calls the probe callback with a valid `pdev`.
58        let dev = unsafe { device::Device::get_device(addr_of_mut!((*pdev).dev)) };
59        // SAFETY: `dev` is guaranteed to be embedded in a valid `struct platform_device` by the
60        // call above.
61        let mut pdev = unsafe { Device::from_dev(dev) };
62
63        let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
64        match T::probe(&mut pdev, info) {
65            Ok(data) => {
66                // Let the `struct platform_device` own a reference of the driver's private data.
67                // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
68                // `struct platform_device`.
69                unsafe { bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign() as _) };
70            }
71            Err(err) => return Error::to_errno(err),
72        }
73
74        0
75    }
76
77    extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
78        // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
79        let ptr = unsafe { bindings::platform_get_drvdata(pdev) };
80
81        // SAFETY: `remove_callback` is only ever called after a successful call to
82        // `probe_callback`, hence it's guaranteed that `ptr` points to a valid and initialized
83        // `KBox<T>` pointer created through `KBox::into_foreign`.
84        let _ = unsafe { KBox::<T>::from_foreign(ptr) };
85    }
86}
87
88impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
89    type IdInfo = T::IdInfo;
90
91    fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
92        T::OF_ID_TABLE
93    }
94}
95
96/// Declares a kernel module that exposes a single platform driver.
97///
98/// # Examples
99///
100/// ```ignore
101/// kernel::module_platform_driver! {
102///     type: MyDriver,
103///     name: "Module name",
104///     author: "Author name",
105///     description: "Description",
106///     license: "GPL v2",
107/// }
108/// ```
109#[macro_export]
110macro_rules! module_platform_driver {
111    ($($f:tt)*) => {
112        $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
113    };
114}
115
116/// The platform driver trait.
117///
118/// Drivers must implement this trait in order to get a platform driver registered.
119///
120/// # Example
121///
122///```
123/// # use kernel::{bindings, c_str, of, platform};
124///
125/// struct MyDriver;
126///
127/// kernel::of_device_table!(
128///     OF_TABLE,
129///     MODULE_OF_TABLE,
130///     <MyDriver as platform::Driver>::IdInfo,
131///     [
132///         (of::DeviceId::new(c_str!("test,device")), ())
133///     ]
134/// );
135///
136/// impl platform::Driver for MyDriver {
137///     type IdInfo = ();
138///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
139///
140///     fn probe(
141///         _pdev: &mut platform::Device,
142///         _id_info: Option<&Self::IdInfo>,
143///     ) -> Result<Pin<KBox<Self>>> {
144///         Err(ENODEV)
145///     }
146/// }
147///```
148pub trait Driver {
149    /// The type holding driver private data about each device id supported by the driver.
150    ///
151    /// TODO: Use associated_type_defaults once stabilized:
152    ///
153    /// type IdInfo: 'static = ();
154    type IdInfo: 'static;
155
156    /// The table of OF device ids supported by the driver.
157    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>>;
158
159    /// Platform driver probe.
160    ///
161    /// Called when a new platform device is added or discovered.
162    /// Implementers should attempt to initialize the device here.
163    fn probe(dev: &mut Device, id_info: Option<&Self::IdInfo>) -> Result<Pin<KBox<Self>>>;
164}
165
166/// The platform device representation.
167///
168/// A platform device is based on an always reference counted `device:Device` instance. Cloning a
169/// platform device, hence, also increments the base device' reference count.
170///
171/// # Invariants
172///
173/// `Device` holds a valid reference of `ARef<device::Device>` whose underlying `struct device` is a
174/// member of a `struct platform_device`.
175#[derive(Clone)]
176pub struct Device(ARef<device::Device>);
177
178impl Device {
179    /// Convert a raw kernel device into a `Device`
180    ///
181    /// # Safety
182    ///
183    /// `dev` must be an `Aref<device::Device>` whose underlying `bindings::device` is a member of a
184    /// `bindings::platform_device`.
185    unsafe fn from_dev(dev: ARef<device::Device>) -> Self {
186        Self(dev)
187    }
188
189    fn as_raw(&self) -> *mut bindings::platform_device {
190        // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
191        // embedded in `struct platform_device`.
192        unsafe { container_of!(self.0.as_raw(), bindings::platform_device, dev) }.cast_mut()
193    }
194}
195
196impl AsRef<device::Device> for Device {
197    fn as_ref(&self) -> &device::Device {
198        &self.0
199    }
200}