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