xref: /linux/rust/kernel/platform.rs (revision 0242623384c767b1156b61b67894b4ecf6682b8b)
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 ///     ) -> 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         ) -> Result<impl PinInit<irq::$reg_type<T>, Error> + 'a> {
305             let request = self.$request_fn(index)?;
306 
307             Ok(irq::$reg_type::<T>::new(
308                 request,
309                 flags,
310                 name,
311                 handler,
312             ))
313         }
314     };
315 }
316 
317 macro_rules! define_irq_accessor_by_name {
318     (
319         $(#[$meta:meta])* $fn_name:ident,
320         $request_fn:ident,
321         $reg_type:ident,
322         $handler_trait:ident
323     ) => {
324         $(#[$meta])*
325         pub fn $fn_name<'a, T: irq::$handler_trait + 'static>(
326             &'a self,
327             flags: irq::Flags,
328             irq_name: &CStr,
329             name: &'static CStr,
330             handler: impl PinInit<T, Error> + 'a,
331         ) -> Result<impl PinInit<irq::$reg_type<T>, Error> + 'a> {
332             let request = self.$request_fn(irq_name)?;
333 
334             Ok(irq::$reg_type::<T>::new(
335                 request,
336                 flags,
337                 name,
338                 handler,
339             ))
340         }
341     };
342 }
343 
344 impl Device<Bound> {
345     /// Returns an [`IrqRequest`] for the IRQ at the given index, if any.
346     pub fn irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
347         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
348         let irq = unsafe { bindings::platform_get_irq(self.as_raw(), index) };
349 
350         if irq < 0 {
351             return Err(Error::from_errno(irq));
352         }
353 
354         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
355         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
356     }
357 
358     /// Returns an [`IrqRequest`] for the IRQ at the given index, but does not
359     /// print an error if the IRQ cannot be obtained.
360     pub fn optional_irq_by_index(&self, index: u32) -> Result<IrqRequest<'_>> {
361         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
362         let irq = unsafe { bindings::platform_get_irq_optional(self.as_raw(), index) };
363 
364         if irq < 0 {
365             return Err(Error::from_errno(irq));
366         }
367 
368         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
369         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
370     }
371 
372     /// Returns an [`IrqRequest`] for the IRQ with the given name, if any.
373     pub fn irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
374         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
375         let irq = unsafe { bindings::platform_get_irq_byname(self.as_raw(), name.as_char_ptr()) };
376 
377         if irq < 0 {
378             return Err(Error::from_errno(irq));
379         }
380 
381         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
382         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
383     }
384 
385     /// Returns an [`IrqRequest`] for the IRQ with the given name, but does not
386     /// print an error if the IRQ cannot be obtained.
387     pub fn optional_irq_by_name(&self, name: &CStr) -> Result<IrqRequest<'_>> {
388         // SAFETY: `self.as_raw` returns a valid pointer to a `struct platform_device`.
389         let irq = unsafe {
390             bindings::platform_get_irq_byname_optional(self.as_raw(), name.as_char_ptr())
391         };
392 
393         if irq < 0 {
394             return Err(Error::from_errno(irq));
395         }
396 
397         // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
398         Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
399     }
400 
401     define_irq_accessor_by_index!(
402         /// Returns a [`irq::Registration`] for the IRQ at the given index.
403         request_irq_by_index,
404         irq_by_index,
405         Registration,
406         Handler
407     );
408     define_irq_accessor_by_name!(
409         /// Returns a [`irq::Registration`] for the IRQ with the given name.
410         request_irq_by_name,
411         irq_by_name,
412         Registration,
413         Handler
414     );
415     define_irq_accessor_by_index!(
416         /// Does the same as [`Self::request_irq_by_index`], except that it does
417         /// not print an error message if the IRQ cannot be obtained.
418         request_optional_irq_by_index,
419         optional_irq_by_index,
420         Registration,
421         Handler
422     );
423     define_irq_accessor_by_name!(
424         /// Does the same as [`Self::request_irq_by_name`], except that it does
425         /// not print an error message if the IRQ cannot be obtained.
426         request_optional_irq_by_name,
427         optional_irq_by_name,
428         Registration,
429         Handler
430     );
431 
432     define_irq_accessor_by_index!(
433         /// Returns a [`irq::ThreadedRegistration`] for the IRQ at the given index.
434         request_threaded_irq_by_index,
435         irq_by_index,
436         ThreadedRegistration,
437         ThreadedHandler
438     );
439     define_irq_accessor_by_name!(
440         /// Returns a [`irq::ThreadedRegistration`] for the IRQ with the given name.
441         request_threaded_irq_by_name,
442         irq_by_name,
443         ThreadedRegistration,
444         ThreadedHandler
445     );
446     define_irq_accessor_by_index!(
447         /// Does the same as [`Self::request_threaded_irq_by_index`], except
448         /// that it does not print an error message if the IRQ cannot be
449         /// obtained.
450         request_optional_threaded_irq_by_index,
451         optional_irq_by_index,
452         ThreadedRegistration,
453         ThreadedHandler
454     );
455     define_irq_accessor_by_name!(
456         /// Does the same as [`Self::request_threaded_irq_by_name`], except that
457         /// it does not print an error message if the IRQ cannot be obtained.
458         request_optional_threaded_irq_by_name,
459         optional_irq_by_name,
460         ThreadedRegistration,
461         ThreadedHandler
462     );
463 }
464 
465 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
466 // argument.
467 kernel::impl_device_context_deref!(unsafe { Device });
468 kernel::impl_device_context_into_aref!(Device);
469 
470 impl crate::dma::Device for Device<device::Core> {}
471 
472 // SAFETY: Instances of `Device` are always reference-counted.
473 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
474     fn inc_ref(&self) {
475         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
476         unsafe { bindings::get_device(self.as_ref().as_raw()) };
477     }
478 
479     unsafe fn dec_ref(obj: NonNull<Self>) {
480         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
481         unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
482     }
483 }
484 
485 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
486     fn as_ref(&self) -> &device::Device<Ctx> {
487         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
488         // `struct platform_device`.
489         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
490 
491         // SAFETY: `dev` points to a valid `struct device`.
492         unsafe { device::Device::from_raw(dev) }
493     }
494 }
495 
496 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
497     type Error = kernel::error::Error;
498 
499     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
500         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
501         // `struct device`.
502         if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
503             return Err(EINVAL);
504         }
505 
506         // SAFETY: We've just verified that the bus type of `dev` equals
507         // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
508         // `struct platform_device` as guaranteed by the corresponding C code.
509         let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
510 
511         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
512         Ok(unsafe { &*pdev.cast() })
513     }
514 }
515 
516 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
517 unsafe impl Send for Device {}
518 
519 // SAFETY: `Device` can be shared among threads because all methods of `Device`
520 // (i.e. `Device<Normal>) are thread safe.
521 unsafe impl Sync for Device {}
522