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