xref: /linux/rust/kernel/platform.rs (revision 2f5606afa4c2bcabd45cb34c92faf93ca5ffe75e)
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::{from_result, to_result, Result},
10     of,
11     prelude::*,
12     types::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::CoreInternal>>() };
70         let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
71 
72         from_result(|| {
73             let data = T::probe(pdev, info)?;
74 
75             pdev.as_ref().set_drvdata(data);
76             Ok(0)
77         })
78     }
79 
80     extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
81         // SAFETY: The platform bus only ever calls the remove callback with a valid pointer to a
82         // `struct platform_device`.
83         //
84         // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
85         let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() };
86 
87         // SAFETY: `remove_callback` is only ever called after a successful call to
88         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
89         // and stored a `Pin<KBox<T>>`.
90         let data = unsafe { pdev.as_ref().drvdata_obtain::<Pin<KBox<T>>>() };
91 
92         T::unbind(pdev, data.as_ref());
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     /// Platform driver unbind.
193     ///
194     /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
195     /// is optional.
196     ///
197     /// This callback serves as a place for drivers to perform teardown operations that require a
198     /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
199     /// operations to gracefully tear down the device.
200     ///
201     /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
202     fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
203         let _ = (dev, this);
204     }
205 }
206 
207 /// The platform device representation.
208 ///
209 /// This structure represents the Rust abstraction for a C `struct platform_device`. The
210 /// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
211 /// code that we get passed from the C side.
212 ///
213 /// # Invariants
214 ///
215 /// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
216 /// the kernel.
217 #[repr(transparent)]
218 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
219     Opaque<bindings::platform_device>,
220     PhantomData<Ctx>,
221 );
222 
223 impl<Ctx: device::DeviceContext> Device<Ctx> {
224     fn as_raw(&self) -> *mut bindings::platform_device {
225         self.0.get()
226     }
227 }
228 
229 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
230 // argument.
231 kernel::impl_device_context_deref!(unsafe { Device });
232 kernel::impl_device_context_into_aref!(Device);
233 
234 // SAFETY: Instances of `Device` are always reference-counted.
235 unsafe impl crate::types::AlwaysRefCounted for Device {
236     fn inc_ref(&self) {
237         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
238         unsafe { bindings::get_device(self.as_ref().as_raw()) };
239     }
240 
241     unsafe fn dec_ref(obj: NonNull<Self>) {
242         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
243         unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
244     }
245 }
246 
247 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
248     fn as_ref(&self) -> &device::Device<Ctx> {
249         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
250         // `struct platform_device`.
251         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
252 
253         // SAFETY: `dev` points to a valid `struct device`.
254         unsafe { device::Device::from_raw(dev) }
255     }
256 }
257 
258 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
259     type Error = kernel::error::Error;
260 
261     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
262         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
263         // `struct device`.
264         if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
265             return Err(EINVAL);
266         }
267 
268         // SAFETY: We've just verified that the bus type of `dev` equals
269         // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
270         // `struct platform_device` as guaranteed by the corresponding C code.
271         let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
272 
273         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
274         Ok(unsafe { &*pdev.cast() })
275     }
276 }
277 
278 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
279 unsafe impl Send for Device {}
280 
281 // SAFETY: `Device` can be shared among threads because all methods of `Device`
282 // (i.e. `Device<Normal>) are thread safe.
283 unsafe impl Sync for Device {}
284