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