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