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