xref: /linux/rust/kernel/platform.rs (revision 880dec12a25890e8f5626f04c58d38003f1a5585)
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, device, driver,
9     error::{to_result, Result},
10     of,
11     prelude::*,
12     types::{ForeignOwnable, Opaque},
13     ThisModule,
14 };
15 
16 use core::{
17     marker::PhantomData,
18     ptr::{addr_of_mut, NonNull},
19 };
20 
21 /// An adapter for the registration of platform drivers.
22 pub struct Adapter<T: Driver>(T);
23 
24 // SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if
25 // a preceding call to `register` has been successful.
26 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
27     type RegType = bindings::platform_driver;
28 
29     unsafe fn register(
30         pdrv: &Opaque<Self::RegType>,
31         name: &'static CStr,
32         module: &'static ThisModule,
33     ) -> Result {
34         let of_table = match T::OF_ID_TABLE {
35             Some(table) => table.as_ptr(),
36             None => core::ptr::null(),
37         };
38 
39         let acpi_table = match T::ACPI_ID_TABLE {
40             Some(table) => table.as_ptr(),
41             None => core::ptr::null(),
42         };
43 
44         // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
45         unsafe {
46             (*pdrv.get()).driver.name = name.as_char_ptr();
47             (*pdrv.get()).probe = Some(Self::probe_callback);
48             (*pdrv.get()).remove = Some(Self::remove_callback);
49             (*pdrv.get()).driver.of_match_table = of_table;
50             (*pdrv.get()).driver.acpi_match_table = acpi_table;
51         }
52 
53         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
54         to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
55     }
56 
57     unsafe fn unregister(pdrv: &Opaque<Self::RegType>) {
58         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
59         unsafe { bindings::platform_driver_unregister(pdrv.get()) };
60     }
61 }
62 
63 impl<T: Driver + 'static> Adapter<T> {
64     extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
65         // SAFETY: The platform bus only ever calls the probe callback with a valid pointer to a
66         // `struct platform_device`.
67         //
68         // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
69         let pdev = unsafe { &*pdev.cast::<Device<device::Core>>() };
70 
71         let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
72         match T::probe(pdev, info) {
73             Ok(data) => {
74                 // Let the `struct platform_device` own a reference of the driver's private data.
75                 // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
76                 // `struct platform_device`.
77                 unsafe { bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign() as _) };
78             }
79             Err(err) => return Error::to_errno(err),
80         }
81 
82         0
83     }
84 
85     extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
86         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
87         let ptr = unsafe { bindings::platform_get_drvdata(pdev) }.cast();
88 
89         // SAFETY: `remove_callback` is only ever called after a successful call to
90         // `probe_callback`, hence it's guaranteed that `ptr` points to a valid and initialized
91         // `KBox<T>` pointer created through `KBox::into_foreign`.
92         let _ = unsafe { KBox::<T>::from_foreign(ptr) };
93     }
94 }
95 
96 impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
97     type IdInfo = T::IdInfo;
98 
99     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
100         T::OF_ID_TABLE
101     }
102 
103     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
104         T::ACPI_ID_TABLE
105     }
106 }
107 
108 /// Declares a kernel module that exposes a single platform driver.
109 ///
110 /// # Examples
111 ///
112 /// ```ignore
113 /// kernel::module_platform_driver! {
114 ///     type: MyDriver,
115 ///     name: "Module name",
116 ///     authors: ["Author name"],
117 ///     description: "Description",
118 ///     license: "GPL v2",
119 /// }
120 /// ```
121 #[macro_export]
122 macro_rules! module_platform_driver {
123     ($($f:tt)*) => {
124         $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
125     };
126 }
127 
128 /// The platform driver trait.
129 ///
130 /// Drivers must implement this trait in order to get a platform driver registered.
131 ///
132 /// # Example
133 ///
134 ///```
135 /// # use kernel::{acpi, bindings, c_str, device::Core, of, platform};
136 ///
137 /// struct MyDriver;
138 ///
139 /// kernel::of_device_table!(
140 ///     OF_TABLE,
141 ///     MODULE_OF_TABLE,
142 ///     <MyDriver as platform::Driver>::IdInfo,
143 ///     [
144 ///         (of::DeviceId::new(c_str!("test,device")), ())
145 ///     ]
146 /// );
147 ///
148 /// kernel::acpi_device_table!(
149 ///     ACPI_TABLE,
150 ///     MODULE_ACPI_TABLE,
151 ///     <MyDriver as platform::Driver>::IdInfo,
152 ///     [
153 ///         (acpi::DeviceId::new(c_str!("LNUXBEEF")), ())
154 ///     ]
155 /// );
156 ///
157 /// impl platform::Driver for MyDriver {
158 ///     type IdInfo = ();
159 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
160 ///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
161 ///
162 ///     fn probe(
163 ///         _pdev: &platform::Device<Core>,
164 ///         _id_info: Option<&Self::IdInfo>,
165 ///     ) -> Result<Pin<KBox<Self>>> {
166 ///         Err(ENODEV)
167 ///     }
168 /// }
169 ///```
170 pub trait Driver: Send {
171     /// The type holding driver private data about each device id supported by the driver.
172     // TODO: Use associated_type_defaults once stabilized:
173     //
174     // ```
175     // type IdInfo: 'static = ();
176     // ```
177     type IdInfo: 'static;
178 
179     /// The table of OF device ids supported by the driver.
180     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
181 
182     /// The table of ACPI device ids supported by the driver.
183     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
184 
185     /// Platform driver probe.
186     ///
187     /// Called when a new platform device is added or discovered.
188     /// Implementers should attempt to initialize the device here.
189     fn probe(dev: &Device<device::Core>, id_info: Option<&Self::IdInfo>)
190         -> Result<Pin<KBox<Self>>>;
191 }
192 
193 /// The platform device representation.
194 ///
195 /// This structure represents the Rust abstraction for a C `struct platform_device`. The
196 /// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
197 /// code that we get passed from the C side.
198 ///
199 /// # Invariants
200 ///
201 /// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
202 /// the kernel.
203 #[repr(transparent)]
204 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
205     Opaque<bindings::platform_device>,
206     PhantomData<Ctx>,
207 );
208 
209 impl<Ctx: device::DeviceContext> Device<Ctx> {
210     fn as_raw(&self) -> *mut bindings::platform_device {
211         self.0.get()
212     }
213 }
214 
215 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
216 // argument.
217 kernel::impl_device_context_deref!(unsafe { Device });
218 kernel::impl_device_context_into_aref!(Device);
219 
220 // SAFETY: Instances of `Device` are always reference-counted.
221 unsafe impl crate::types::AlwaysRefCounted for Device {
222     fn inc_ref(&self) {
223         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
224         unsafe { bindings::get_device(self.as_ref().as_raw()) };
225     }
226 
227     unsafe fn dec_ref(obj: NonNull<Self>) {
228         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
229         unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
230     }
231 }
232 
233 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
234     fn as_ref(&self) -> &device::Device<Ctx> {
235         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
236         // `struct platform_device`.
237         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
238 
239         // SAFETY: `dev` points to a valid `struct device`.
240         unsafe { device::Device::as_ref(dev) }
241     }
242 }
243 
244 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
245     type Error = kernel::error::Error;
246 
247     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
248         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
249         // `struct device`.
250         if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
251             return Err(EINVAL);
252         }
253 
254         // SAFETY: We've just verified that the bus type of `dev` equals
255         // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
256         // `struct platform_device` as guaranteed by the corresponding C code.
257         let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
258 
259         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
260         Ok(unsafe { &*pdev.cast() })
261     }
262 }
263 
264 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
265 unsafe impl Send for Device {}
266 
267 // SAFETY: `Device` can be shared among threads because all methods of `Device`
268 // (i.e. `Device<Normal>) are thread safe.
269 unsafe impl Sync for Device {}
270