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,
9    device::{self, Bound},
10    driver,
11    error::{from_result, to_result, Result},
12    io::{mem::IoRequest, Resource},
13    of,
14    prelude::*,
15    types::Opaque,
16    ThisModule,
17};
18
19use core::{
20    marker::PhantomData,
21    ptr::{addr_of_mut, NonNull},
22};
23
24/// An adapter for the registration of platform drivers.
25pub struct Adapter<T: Driver>(T);
26
27// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
28// a preceding call to `register` has been successful.
29unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
30    type RegType = bindings::platform_driver;
31
32    unsafe fn register(
33        pdrv: &Opaque<Self::RegType>,
34        name: &'static CStr,
35        module: &'static ThisModule,
36    ) -> Result {
37        let of_table = match T::OF_ID_TABLE {
38            Some(table) => table.as_ptr(),
39            None => core::ptr::null(),
40        };
41
42        let acpi_table = match T::ACPI_ID_TABLE {
43            Some(table) => table.as_ptr(),
44            None => core::ptr::null(),
45        };
46
47        // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
48        unsafe {
49            (*pdrv.get()).driver.name = name.as_char_ptr();
50            (*pdrv.get()).probe = Some(Self::probe_callback);
51            (*pdrv.get()).remove = Some(Self::remove_callback);
52            (*pdrv.get()).driver.of_match_table = of_table;
53            (*pdrv.get()).driver.acpi_match_table = acpi_table;
54        }
55
56        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
57        to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
58    }
59
60    unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
61        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
62        unsafe { bindings::platform_driver_unregister(pdrv.get()) };
63    }
64}
65
66impl<T: Driver + 'static> Adapter<T> {
67    extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
68        // SAFETY: The platform bus only ever calls the probe callback with a valid pointer to a
69        // `struct platform_device`.
70        //
71        // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
72        let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
73        let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
74
75        from_result(|| {
76            let data = T::probe(pdev, info)?;
77
78            pdev.as_ref().set_drvdata(data);
79            Ok(0)
80        })
81    }
82
83    extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
84        // SAFETY: The platform bus only ever calls the remove callback with a valid pointer to a
85        // `struct platform_device`.
86        //
87        // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
88        let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
89
90        // SAFETY: `remove_callback` is only ever called after a successful call to
91        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
92        // and stored a `Pin<KBox<T>>`.
93        let data = unsafe { pdev.as_ref().drvdata_obtain::<Pin<KBox<T>>>() };
94
95        T::unbind(pdev, data.as_ref());
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    /// Platform driver unbind.
196    ///
197    /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
198    /// is optional.
199    ///
200    /// This callback serves as a place for drivers to perform teardown operations that require a
201    /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
202    /// operations to gracefully tear down the device.
203    ///
204    /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
205    fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
206        let _ = (dev, this);
207    }
208}
209
210/// The platform device representation.
211///
212/// This structure represents the Rust abstraction for a C `struct platform_device`. The
213/// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
214/// code that we get passed from the C side.
215///
216/// # Invariants
217///
218/// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
219/// the kernel.
220#[repr(transparent)]
221pub struct Device<Ctx: device::DeviceContext = device::Normal>(
222    Opaque<bindings::platform_device>,
223    PhantomData<Ctx>,
224);
225
226impl<Ctx: device::DeviceContext> Device<Ctx> {
227    fn as_raw(&self) -> *mut bindings::platform_device {
228        self.0.get()
229    }
230
231    /// Returns the resource at `index`, if any.
232    pub fn resource_by_index(&self, index: u32) -> Option<&Resource> {
233        // SAFETY: `self.as_raw()` returns a valid pointer to a `struct platform_device`.
234        let resource = unsafe {
235            bindings::platform_get_resource(self.as_raw(), bindings::IORESOURCE_MEM, index)
236        };
237
238        if resource.is_null() {
239            return None;
240        }
241
242        // SAFETY: `resource` is a valid pointer to a `struct resource` as
243        // returned by `platform_get_resource`.
244        Some(unsafe { Resource::from_raw(resource) })
245    }
246
247    /// Returns the resource with a given `name`, if any.
248    pub fn resource_by_name(&self, name: &CStr) -> Option<&Resource> {
249        // SAFETY: `self.as_raw()` returns a valid pointer to a `struct
250        // platform_device` and `name` points to a valid C string.
251        let resource = unsafe {
252            bindings::platform_get_resource_byname(
253                self.as_raw(),
254                bindings::IORESOURCE_MEM,
255                name.as_char_ptr(),
256            )
257        };
258
259        if resource.is_null() {
260            return None;
261        }
262
263        // SAFETY: `resource` is a valid pointer to a `struct resource` as
264        // returned by `platform_get_resource`.
265        Some(unsafe { Resource::from_raw(resource) })
266    }
267}
268
269impl Device<Bound> {
270    /// Returns an `IoRequest` for the resource at `index`, if any.
271    pub fn io_request_by_index(&self, index: u32) -> Option<IoRequest<'_>> {
272        self.resource_by_index(index)
273            // SAFETY: `resource` is a valid resource for `&self` during the
274            // lifetime of the `IoRequest`.
275            .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
276    }
277
278    /// Returns an `IoRequest` for the resource with a given `name`, if any.
279    pub fn io_request_by_name(&self, name: &CStr) -> Option<IoRequest<'_>> {
280        self.resource_by_name(name)
281            // SAFETY: `resource` is a valid resource for `&self` during the
282            // lifetime of the `IoRequest`.
283            .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
284    }
285}
286
287// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
288// argument.
289kernel::impl_device_context_deref!(unsafe { Device });
290kernel::impl_device_context_into_aref!(Device);
291
292impl crate::dma::Device for Device<device::Core> {}
293
294// SAFETY: Instances of `Device` are always reference-counted.
295unsafe impl crate::types::AlwaysRefCounted for Device {
296    fn inc_ref(&self) {
297        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
298        unsafe { bindings::get_device(self.as_ref().as_raw()) };
299    }
300
301    unsafe fn dec_ref(obj: NonNull<Self>) {
302        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
303        unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
304    }
305}
306
307impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
308    fn as_ref(&self) -> &device::Device<Ctx> {
309        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
310        // `struct platform_device`.
311        let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
312
313        // SAFETY: `dev` points to a valid `struct device`.
314        unsafe { device::Device::from_raw(dev) }
315    }
316}
317
318impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
319    type Error = kernel::error::Error;
320
321    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
322        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
323        // `struct device`.
324        if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
325            return Err(EINVAL);
326        }
327
328        // SAFETY: We've just verified that the bus type of `dev` equals
329        // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
330        // `struct platform_device` as guaranteed by the corresponding C code.
331        let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
332
333        // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
334        Ok(unsafe { &*pdev.cast() })
335    }
336}
337
338// SAFETY: A `Device` is always reference-counted and can be released from any thread.
339unsafe impl Send for Device {}
340
341// SAFETY: `Device` can be shared among threads because all methods of `Device`
342// (i.e. `Device<Normal>) are thread safe.
343unsafe impl Sync for Device {}