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