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,
9    bindings,
10    container_of,
11    device::{
12        self,
13        Bound, //
14    },
15    driver,
16    error::{
17        from_result,
18        to_result, //
19    },
20    io::{
21        mem::IoRequest,
22        Resource, //
23    },
24    irq::{
25        self,
26        IrqRequest, //
27    },
28    of,
29    prelude::*,
30    types::Opaque,
31    ThisModule, //
32};
33
34use core::{
35    marker::PhantomData,
36    mem::offset_of,
37    ptr::{
38        addr_of_mut,
39        NonNull, //
40    },
41};
42
43/// An adapter for the registration of platform drivers.
44pub struct Adapter<T: Driver>(T);
45
46// SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
47// a preceding call to `register` has been successful.
48unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
49    type RegType = bindings::platform_driver;
50
51    unsafe fn register(
52        pdrv: &Opaque<Self::RegType>,
53        name: &'static CStr,
54        module: &'static ThisModule,
55    ) -> Result {
56        let of_table = match T::OF_ID_TABLE {
57            Some(table) => table.as_ptr(),
58            None => core::ptr::null(),
59        };
60
61        let acpi_table = match T::ACPI_ID_TABLE {
62            Some(table) => table.as_ptr(),
63            None => core::ptr::null(),
64        };
65
66        // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
67        unsafe {
68            (*pdrv.get()).driver.name = name.as_char_ptr();
69            (*pdrv.get()).probe = Some(Self::probe_callback);
70            (*pdrv.get()).remove = Some(Self::remove_callback);
71            (*pdrv.get()).driver.of_match_table = of_table;
72            (*pdrv.get()).driver.acpi_match_table = acpi_table;
73        }
74
75        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
76        to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
77    }
78
79    unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
80        // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
81        unsafe { bindings::platform_driver_unregister(pdrv.get()) };
82    }
83}
84
85impl<T: Driver + 'static> Adapter<T> {
86    extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
87        // SAFETY: The platform bus only ever calls the probe callback with a valid pointer to a
88        // `struct platform_device`.
89        //
90        // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
91        let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
92        let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
93
94        from_result(|| {
95            let data = T::probe(pdev, info);
96
97            pdev.as_ref().set_drvdata(data)?;
98            Ok(0)
99        })
100    }
101
102    extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
103        // SAFETY: The platform bus only ever calls the remove callback with a valid pointer to a
104        // `struct platform_device`.
105        //
106        // INVARIANT: `pdev` is valid for the duration of `remove_callback()`.
107        let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
108
109        // SAFETY: `remove_callback` is only ever called after a successful call to
110        // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
111        // and stored a `Pin<KBox<T>>`.
112        let data = unsafe { pdev.as_ref().drvdata_obtain::<T>() };
113
114        T::unbind(pdev, data.as_ref());
115    }
116}
117
118impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
119    type IdInfo = T::IdInfo;
120
121    fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
122        T::OF_ID_TABLE
123    }
124
125    fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
126        T::ACPI_ID_TABLE
127    }
128}
129
130/// Declares a kernel module that exposes a single platform driver.
131///
132/// # Examples
133///
134/// ```ignore
135/// kernel::module_platform_driver! {
136///     type: MyDriver,
137///     name: "Module name",
138///     authors: ["Author name"],
139///     description: "Description",
140///     license: "GPL v2",
141/// }
142/// ```
143#[macro_export]
144macro_rules! module_platform_driver {
145    ($($f:tt)*) => {
146        $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
147    };
148}
149
150/// The platform driver trait.
151///
152/// Drivers must implement this trait in order to get a platform driver registered.
153///
154/// # Examples
155///
156///```
157/// # use kernel::{
158/// #     acpi,
159/// #     bindings,
160/// #     device::Core,
161/// #     of,
162/// #     platform,
163/// # };
164/// struct MyDriver;
165///
166/// kernel::of_device_table!(
167///     OF_TABLE,
168///     MODULE_OF_TABLE,
169///     <MyDriver as platform::Driver>::IdInfo,
170///     [
171///         (of::DeviceId::new(c"test,device"), ())
172///     ]
173/// );
174///
175/// kernel::acpi_device_table!(
176///     ACPI_TABLE,
177///     MODULE_ACPI_TABLE,
178///     <MyDriver as platform::Driver>::IdInfo,
179///     [
180///         (acpi::DeviceId::new(c"LNUXBEEF"), ())
181///     ]
182/// );
183///
184/// impl platform::Driver for MyDriver {
185///     type IdInfo = ();
186///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
187///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
188///
189///     fn probe(
190///         _pdev: &platform::Device<Core>,
191///         _id_info: Option<&Self::IdInfo>,
192///     ) -> impl PinInit<Self, Error> {
193///         Err(ENODEV)
194///     }
195/// }
196///```
197pub trait Driver: Send {
198    /// The type holding driver private data about each device id supported by the driver.
199    // TODO: Use associated_type_defaults once stabilized:
200    //
201    // ```
202    // type IdInfo: 'static = ();
203    // ```
204    type IdInfo: 'static;
205
206    /// The table of OF device ids supported by the driver.
207    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
208
209    /// The table of ACPI device ids supported by the driver.
210    const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
211
212    /// Platform driver probe.
213    ///
214    /// Called when a new platform device is added or discovered.
215    /// Implementers should attempt to initialize the device here.
216    fn probe(
217        dev: &Device<device::Core>,
218        id_info: Option<&Self::IdInfo>,
219    ) -> impl PinInit<Self, Error>;
220
221    /// Platform driver unbind.
222    ///
223    /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
224    /// is optional.
225    ///
226    /// This callback serves as a place for drivers to perform teardown operations that require a
227    /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
228    /// operations to gracefully tear down the device.
229    ///
230    /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
231    fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
232        let _ = (dev, this);
233    }
234}
235
236/// The platform device representation.
237///
238/// This structure represents the Rust abstraction for a C `struct platform_device`. The
239/// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
240/// code that we get passed from the C side.
241///
242/// # Invariants
243///
244/// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
245/// the kernel.
246#[repr(transparent)]
247pub struct Device<Ctx: device::DeviceContext = device::Normal>(
248    Opaque<bindings::platform_device>,
249    PhantomData<Ctx>,
250);
251
252impl<Ctx: device::DeviceContext> Device<Ctx> {
253    fn as_raw(&self) -> *mut bindings::platform_device {
254        self.0.get()
255    }
256
257    /// Returns the resource at `index`, if any.
258    pub fn resource_by_index(&self, index: u32) -> Option<&Resource> {
259        // SAFETY: `self.as_raw()` returns a valid pointer to a `struct platform_device`.
260        let resource = unsafe {
261            bindings::platform_get_resource(self.as_raw(), bindings::IORESOURCE_MEM, index)
262        };
263
264        if resource.is_null() {
265            return None;
266        }
267
268        // SAFETY: `resource` is a valid pointer to a `struct resource` as
269        // returned by `platform_get_resource`.
270        Some(unsafe { Resource::from_raw(resource) })
271    }
272
273    /// Returns the resource with a given `name`, if any.
274    pub fn resource_by_name(&self, name: &CStr) -> Option<&Resource> {
275        // SAFETY: `self.as_raw()` returns a valid pointer to a `struct
276        // platform_device` and `name` points to a valid C string.
277        let resource = unsafe {
278            bindings::platform_get_resource_byname(
279                self.as_raw(),
280                bindings::IORESOURCE_MEM,
281                name.as_char_ptr(),
282            )
283        };
284
285        if resource.is_null() {
286            return None;
287        }
288
289        // SAFETY: `resource` is a valid pointer to a `struct resource` as
290        // returned by `platform_get_resource`.
291        Some(unsafe { Resource::from_raw(resource) })
292    }
293}
294
295impl Device<Bound> {
296    /// Returns an `IoRequest` for the resource at `index`, if any.
297    pub fn io_request_by_index(&self, index: u32) -> Option<IoRequest<'_>> {
298        self.resource_by_index(index)
299            // SAFETY: `resource` is a valid resource for `&self` during the
300            // lifetime of the `IoRequest`.
301            .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
302    }
303
304    /// Returns an `IoRequest` for the resource with a given `name`, if any.
305    pub fn io_request_by_name(&self, name: &CStr) -> Option<IoRequest<'_>> {
306        self.resource_by_name(name)
307            // SAFETY: `resource` is a valid resource for `&self` during the
308            // lifetime of the `IoRequest`.
309            .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
310    }
311}
312
313// SAFETY: `platform::Device` is a transparent wrapper of `struct platform_device`.
314// The offset is guaranteed to point to a valid device field inside `platform::Device`.
315unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
316    const OFFSET: usize = offset_of!(bindings::platform_device, dev);
317}
318
319macro_rules! define_irq_accessor_by_index {
320    (
321        $(#[$meta:meta])* $fn_name:ident,
322        $request_fn:ident,
323        $reg_type:ident,
324        $handler_trait:ident
325    ) => {
326        $(#[$meta])*
327        pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
328            &'a self,
329            flags: irq::Flags,
330            index: u32,
331            name: &'static CStr,
332            handler: impl PinInit<T, Error> + 'a,
333        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a {
334            pin_init::pin_init_scope(move || {
335                let request = self.$request_fn(index)?;
336
337                Ok(irq::$reg_type::<T>::new(
338                    request,
339                    flags,
340                    name,
341                    handler,
342                ))
343            })
344        }
345    };
346}
347
348macro_rules! define_irq_accessor_by_name {
349    (
350        $(#[$meta:meta])* $fn_name:ident,
351        $request_fn:ident,
352        $reg_type:ident,
353        $handler_trait:ident
354    ) => {
355        $(#[$meta])*
356        pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
357            &'a self,
358            flags: irq::Flags,
359            irq_name: &'a CStr,
360            name: &'static CStr,
361            handler: impl PinInit<T, Error> + 'a,
362        ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a {
363            pin_init::pin_init_scope(move || {
364                let request = self.$request_fn(irq_name)?;
365
366                Ok(irq::$reg_type::<T>::new(
367                    request,
368                    flags,
369                    name,
370                    handler,
371                ))
372            })
373        }
374    };
375}
376
377impl Device<Bound> {
378    /// Returns an [`IrqRequest`] for the IRQ at the given index, if any.
379    pub fn irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
380        // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
381        let irq = unsafe { bindings::platform_get_irq(self.as_raw(), index) };
382
383        if irq < 0 {
384            return Err(Error::from_errno(irq));
385        }
386
387        // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
388        Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
389    }
390
391    /// Returns an [`IrqRequest`] for the IRQ at the given index, but does not
392    /// print an error if the IRQ cannot be obtained.
393    pub fn optional_irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
394        // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
395        let irq = unsafe { bindings::platform_get_irq_optional(self.as_raw(), index) };
396
397        if irq < 0 {
398            return Err(Error::from_errno(irq));
399        }
400
401        // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
402        Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
403    }
404
405    /// Returns an [`IrqRequest`] for the IRQ with the given name, if any.
406    pub fn irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
407        // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
408        let irq = unsafe { bindings::platform_get_irq_byname(self.as_raw(), name.as_char_ptr()) };
409
410        if irq < 0 {
411            return Err(Error::from_errno(irq));
412        }
413
414        // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
415        Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
416    }
417
418    /// Returns an [`IrqRequest`] for the IRQ with the given name, but does not
419    /// print an error if the IRQ cannot be obtained.
420    pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
421        // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
422        let irq = unsafe {
423            bindings::platform_get_irq_byname_optional(self.as_raw(), name.as_char_ptr())
424        };
425
426        if irq < 0 {
427            return Err(Error::from_errno(irq));
428        }
429
430        // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
431        Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
432    }
433
434    define_irq_accessor_by_index!(
435        /// Returns a [`irq::Registration`] for the IRQ at the given index.
436        request_irq_by_index,
437        irq_by_index,
438        Registration,
439        Handler
440    );
441    define_irq_accessor_by_name!(
442        /// Returns a [`irq::Registration`] for the IRQ with the given name.
443        request_irq_by_name,
444        irq_by_name,
445        Registration,
446        Handler
447    );
448    define_irq_accessor_by_index!(
449        /// Does the same as [`Self::request_irq_by_index`], except that it does
450        /// not print an error message if the IRQ cannot be obtained.
451        request_optional_irq_by_index,
452        optional_irq_by_index,
453        Registration,
454        Handler
455    );
456    define_irq_accessor_by_name!(
457        /// Does the same as [`Self::request_irq_by_name`], except that it does
458        /// not print an error message if the IRQ cannot be obtained.
459        request_optional_irq_by_name,
460        optional_irq_by_name,
461        Registration,
462        Handler
463    );
464
465    define_irq_accessor_by_index!(
466        /// Returns a [`irq::ThreadedRegistration`] for the IRQ at the given index.
467        request_threaded_irq_by_index,
468        irq_by_index,
469        ThreadedRegistration,
470        ThreadedHandler
471    );
472    define_irq_accessor_by_name!(
473        /// Returns a [`irq::ThreadedRegistration`] for the IRQ with the given name.
474        request_threaded_irq_by_name,
475        irq_by_name,
476        ThreadedRegistration,
477        ThreadedHandler
478    );
479    define_irq_accessor_by_index!(
480        /// Does the same as [`Self::request_threaded_irq_by_index`], except
481        /// that it does not print an error message if the IRQ cannot be
482        /// obtained.
483        request_optional_threaded_irq_by_index,
484        optional_irq_by_index,
485        ThreadedRegistration,
486        ThreadedHandler
487    );
488    define_irq_accessor_by_name!(
489        /// Does the same as [`Self::request_threaded_irq_by_name`], except that
490        /// it does not print an error message if the IRQ cannot be obtained.
491        request_optional_threaded_irq_by_name,
492        optional_irq_by_name,
493        ThreadedRegistration,
494        ThreadedHandler
495    );
496}
497
498// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
499// argument.
500kernel::impl_device_context_deref!(unsafe { Device });
501kernel::impl_device_context_into_aref!(Device);
502
503impl crate::dma::Device for Device<device::Core> {}
504
505// SAFETY: Instances of `Device` are always reference-counted.
506unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
507    fn inc_ref(&self) {
508        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
509        unsafe { bindings::get_device(self.as_ref().as_raw()) };
510    }
511
512    unsafe fn dec_ref(obj: NonNull<Self>) {
513        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
514        unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
515    }
516}
517
518impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
519    fn as_ref(&self) -> &device::Device<Ctx> {
520        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
521        // `struct platform_device`.
522        let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
523
524        // SAFETY: `dev` points to a valid `struct device`.
525        unsafe { device::Device::from_raw(dev) }
526    }
527}
528
529impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
530    type Error = kernel::error::Error;
531
532    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
533        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
534        // `struct device`.
535        if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
536            return Err(EINVAL);
537        }
538
539        // SAFETY: We've just verified that the bus type of `dev` equals
540        // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
541        // `struct platform_device` as guaranteed by the corresponding C code.
542        let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
543
544        // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
545        Ok(unsafe { &*pdev.cast() })
546    }
547}
548
549// SAFETY: A `Device` is always reference-counted and can be released from any thread.
550unsafe impl Send for Device {}
551
552// SAFETY: `Device` can be shared among threads because all methods of `Device`
553// (i.e. `Device<Normal>) are thread safe.
554unsafe impl Sync for Device {}