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