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