xref: /linux/rust/kernel/platform.rs (revision d05b8e97690fa19be39f0af03e7f117f601b6319)
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::<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 ///     ) -> impl PinInit<Self, Error> {
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(
194         dev: &Device<device::Core>,
195         id_info: Option<&Self::IdInfo>,
196     ) -> impl PinInit<Self, Error>;
197 
198     /// Platform driver unbind.
199     ///
200     /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
201     /// is optional.
202     ///
203     /// This callback serves as a place for drivers to perform teardown operations that require a
204     /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
205     /// operations to gracefully tear down the device.
206     ///
207     /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
208     fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
209         let _ = (dev, this);
210     }
211 }
212 
213 /// The platform device representation.
214 ///
215 /// This structure represents the Rust abstraction for a C `struct platform_device`. The
216 /// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
217 /// code that we get passed from the C side.
218 ///
219 /// # Invariants
220 ///
221 /// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
222 /// the kernel.
223 #[repr(transparent)]
224 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
225     Opaque<bindings::platform_device>,
226     PhantomData<Ctx>,
227 );
228 
229 impl<Ctx: device::DeviceContext> Device<Ctx> {
230     fn as_raw(&self) -> *mut bindings::platform_device {
231         self.0.get()
232     }
233 
234     /// Returns the resource at `index`, if any.
235     pub fn resource_by_index(&self, index: u32) -> Option<&Resource> {
236         // SAFETY: `self.as_raw()` returns a valid pointer to a `struct platform_device`.
237         let resource = unsafe {
238             bindings::platform_get_resource(self.as_raw(), bindings::IORESOURCE_MEM, index)
239         };
240 
241         if resource.is_null() {
242             return None;
243         }
244 
245         // SAFETY: `resource` is a valid pointer to a `struct resource` as
246         // returned by `platform_get_resource`.
247         Some(unsafe { Resource::from_raw(resource) })
248     }
249 
250     /// Returns the resource with a given `name`, if any.
251     pub fn resource_by_name(&self, name: &CStr) -> Option<&Resource> {
252         // SAFETY: `self.as_raw()` returns a valid pointer to a `struct
253         // platform_device` and `name` points to a valid C string.
254         let resource = unsafe {
255             bindings::platform_get_resource_byname(
256                 self.as_raw(),
257                 bindings::IORESOURCE_MEM,
258                 name.as_char_ptr(),
259             )
260         };
261 
262         if resource.is_null() {
263             return None;
264         }
265 
266         // SAFETY: `resource` is a valid pointer to a `struct resource` as
267         // returned by `platform_get_resource`.
268         Some(unsafe { Resource::from_raw(resource) })
269     }
270 }
271 
272 impl Device<Bound> {
273     /// Returns an `IoRequest` for the resource at `index`, if any.
274     pub fn io_request_by_index(&self, index: u32) -> Option<IoRequest<'_>> {
275         self.resource_by_index(index)
276             // SAFETY: `resource` is a valid resource for `&self` during the
277             // lifetime of the `IoRequest`.
278             .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
279     }
280 
281     /// Returns an `IoRequest` for the resource with a given `name`, if any.
282     pub fn io_request_by_name(&self, name: &CStr) -> Option<IoRequest<'_>> {
283         self.resource_by_name(name)
284             // SAFETY: `resource` is a valid resource for `&self` during the
285             // lifetime of the `IoRequest`.
286             .map(|resource| unsafe { IoRequest::new(self.as_ref(), resource) })
287     }
288 }
289 
290 macro_rules! define_irq_accessor_by_index {
291     (
292         $(#[$meta:meta])* $fn_name:ident,
293         $request_fn:ident,
294         $reg_type:ident,
295         $handler_trait:ident
296     ) => {
297         $(#[$meta])*
298         pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
299             &'a self,
300             flags: irq::Flags,
301             index: u32,
302             name: &'static CStr,
303             handler: impl PinInit<T, Error> + 'a,
304         ) -> impl PinInit<irq::$reg_type<T>, Error> + 'a {
305             pin_init::pin_init_scope(move || {
306                 let request = self.$request_fn(index)?;
307 
308                 Ok(irq::$reg_type::<T>::new(
309                     request,
310                     flags,
311                     name,
312                     handler,
313                 ))
314             })
315         }
316     };
317 }
318 
319 macro_rules! define_irq_accessor_by_name {
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             irq_name: &'a CStr,
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(irq_name)?;
336 
337                 Ok(irq::$reg_type::<T>::new(
338                     request,
339                     flags,
340                     name,
341                     handler,
342                 ))
343             })
344         }
345     };
346 }
347 
348 impl Device<Bound> {
349     /// Returns an [`IrqRequest`] for the IRQ at the given index, if any.
350     pub fn irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
351         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
352         let irq = unsafe { bindings::platform_get_irq(self.as_raw(), index) };
353 
354         if irq < 0 {
355             return Err(Error::from_errno(irq));
356         }
357 
358         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
359         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
360     }
361 
362     /// Returns an [`IrqRequest`] for the IRQ at the given index, but does not
363     /// print an error if the IRQ cannot be obtained.
364     pub fn optional_irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
365         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
366         let irq = unsafe { bindings::platform_get_irq_optional(self.as_raw(), index) };
367 
368         if irq < 0 {
369             return Err(Error::from_errno(irq));
370         }
371 
372         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
373         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
374     }
375 
376     /// Returns an [`IrqRequest`] for the IRQ with the given name, if any.
377     pub fn irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
378         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
379         let irq = unsafe { bindings::platform_get_irq_byname(self.as_raw(), name.as_char_ptr()) };
380 
381         if irq < 0 {
382             return Err(Error::from_errno(irq));
383         }
384 
385         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
386         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
387     }
388 
389     /// Returns an [`IrqRequest`] for the IRQ with the given name, but does not
390     /// print an error if the IRQ cannot be obtained.
391     pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
392         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
393         let irq = unsafe {
394             bindings::platform_get_irq_byname_optional(self.as_raw(), name.as_char_ptr())
395         };
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     define_irq_accessor_by_index!(
406         /// Returns a [`irq::Registration`] for the IRQ at the given index.
407         request_irq_by_index,
408         irq_by_index,
409         Registration,
410         Handler
411     );
412     define_irq_accessor_by_name!(
413         /// Returns a [`irq::Registration`] for the IRQ with the given name.
414         request_irq_by_name,
415         irq_by_name,
416         Registration,
417         Handler
418     );
419     define_irq_accessor_by_index!(
420         /// Does the same as [`Self::request_irq_by_index`], except that it does
421         /// not print an error message if the IRQ cannot be obtained.
422         request_optional_irq_by_index,
423         optional_irq_by_index,
424         Registration,
425         Handler
426     );
427     define_irq_accessor_by_name!(
428         /// Does the same as [`Self::request_irq_by_name`], except that it does
429         /// not print an error message if the IRQ cannot be obtained.
430         request_optional_irq_by_name,
431         optional_irq_by_name,
432         Registration,
433         Handler
434     );
435 
436     define_irq_accessor_by_index!(
437         /// Returns a [`irq::ThreadedRegistration`] for the IRQ at the given index.
438         request_threaded_irq_by_index,
439         irq_by_index,
440         ThreadedRegistration,
441         ThreadedHandler
442     );
443     define_irq_accessor_by_name!(
444         /// Returns a [`irq::ThreadedRegistration`] for the IRQ with the given name.
445         request_threaded_irq_by_name,
446         irq_by_name,
447         ThreadedRegistration,
448         ThreadedHandler
449     );
450     define_irq_accessor_by_index!(
451         /// Does the same as [`Self::request_threaded_irq_by_index`], except
452         /// that it does not print an error message if the IRQ cannot be
453         /// obtained.
454         request_optional_threaded_irq_by_index,
455         optional_irq_by_index,
456         ThreadedRegistration,
457         ThreadedHandler
458     );
459     define_irq_accessor_by_name!(
460         /// Does the same as [`Self::request_threaded_irq_by_name`], except that
461         /// it does not print an error message if the IRQ cannot be obtained.
462         request_optional_threaded_irq_by_name,
463         optional_irq_by_name,
464         ThreadedRegistration,
465         ThreadedHandler
466     );
467 }
468 
469 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
470 // argument.
471 kernel::impl_device_context_deref!(unsafe { Device });
472 kernel::impl_device_context_into_aref!(Device);
473 
474 impl crate::dma::Device for Device<device::Core> {}
475 
476 // SAFETY: Instances of `Device` are always reference-counted.
477 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
478     fn inc_ref(&self) {
479         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
480         unsafe { bindings::get_device(self.as_ref().as_raw()) };
481     }
482 
483     unsafe fn dec_ref(obj: NonNull<Self>) {
484         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
485         unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
486     }
487 }
488 
489 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
490     fn as_ref(&self) -> &device::Device<Ctx> {
491         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
492         // `struct platform_device`.
493         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
494 
495         // SAFETY: `dev` points to a valid `struct device`.
496         unsafe { device::Device::from_raw(dev) }
497     }
498 }
499 
500 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
501     type Error = kernel::error::Error;
502 
503     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
504         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
505         // `struct device`.
506         if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
507             return Err(EINVAL);
508         }
509 
510         // SAFETY: We've just verified that the bus type of `dev` equals
511         // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
512         // `struct platform_device` as guaranteed by the corresponding C code.
513         let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
514 
515         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
516         Ok(unsafe { &*pdev.cast() })
517     }
518 }
519 
520 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
521 unsafe impl Send for Device {}
522 
523 // SAFETY: `Device` can be shared among threads because all methods of `Device`
524 // (i.e. `Device<Normal>) are thread safe.
525 unsafe impl Sync for Device {}
526