Skip to main content

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