xref: /linux/rust/kernel/platform.rs (revision f0a68a912c673d8899d863c2f01f1ef7006e0b11)
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 _ = unsafe { pdev.as_ref().drvdata_obtain::<Pin<KBox<T>>>() };
91     }
92 }
93 
94 impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
95     type IdInfo = T::IdInfo;
96 
97     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
98         T::OF_ID_TABLE
99     }
100 
101     fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> {
102         T::ACPI_ID_TABLE
103     }
104 }
105 
106 /// Declares a kernel module that exposes a single platform driver.
107 ///
108 /// # Examples
109 ///
110 /// ```ignore
111 /// kernel::module_platform_driver! {
112 ///     type: MyDriver,
113 ///     name: "Module name",
114 ///     authors: ["Author name"],
115 ///     description: "Description",
116 ///     license: "GPL v2",
117 /// }
118 /// ```
119 #[macro_export]
120 macro_rules! module_platform_driver {
121     ($($f:tt)*) => {
122         $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
123     };
124 }
125 
126 /// The platform driver trait.
127 ///
128 /// Drivers must implement this trait in order to get a platform driver registered.
129 ///
130 /// # Example
131 ///
132 ///```
133 /// # use kernel::{acpi, bindings, c_str, device::Core, of, platform};
134 ///
135 /// struct MyDriver;
136 ///
137 /// kernel::of_device_table!(
138 ///     OF_TABLE,
139 ///     MODULE_OF_TABLE,
140 ///     <MyDriver as platform::Driver>::IdInfo,
141 ///     [
142 ///         (of::DeviceId::new(c_str!("test,device")), ())
143 ///     ]
144 /// );
145 ///
146 /// kernel::acpi_device_table!(
147 ///     ACPI_TABLE,
148 ///     MODULE_ACPI_TABLE,
149 ///     <MyDriver as platform::Driver>::IdInfo,
150 ///     [
151 ///         (acpi::DeviceId::new(c_str!("LNUXBEEF")), ())
152 ///     ]
153 /// );
154 ///
155 /// impl platform::Driver for MyDriver {
156 ///     type IdInfo = ();
157 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
158 ///     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = Some(&ACPI_TABLE);
159 ///
160 ///     fn probe(
161 ///         _pdev: &platform::Device<Core>,
162 ///         _id_info: Option<&Self::IdInfo>,
163 ///     ) -> Result<Pin<KBox<Self>>> {
164 ///         Err(ENODEV)
165 ///     }
166 /// }
167 ///```
168 pub trait Driver: Send {
169     /// The type holding driver private data about each device id supported by the driver.
170     // TODO: Use associated_type_defaults once stabilized:
171     //
172     // ```
173     // type IdInfo: 'static = ();
174     // ```
175     type IdInfo: 'static;
176 
177     /// The table of OF device ids supported by the driver.
178     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
179 
180     /// The table of ACPI device ids supported by the driver.
181     const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None;
182 
183     /// Platform driver probe.
184     ///
185     /// Called when a new platform device is added or discovered.
186     /// Implementers should attempt to initialize the device here.
187     fn probe(dev: &Device<device::Core>, id_info: Option<&Self::IdInfo>)
188         -> Result<Pin<KBox<Self>>>;
189 }
190 
191 /// The platform device representation.
192 ///
193 /// This structure represents the Rust abstraction for a C `struct platform_device`. The
194 /// implementation abstracts the usage of an already existing C `struct platform_device` within Rust
195 /// code that we get passed from the C side.
196 ///
197 /// # Invariants
198 ///
199 /// A [`Device`] instance represents a valid `struct platform_device` created by the C portion of
200 /// the kernel.
201 #[repr(transparent)]
202 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
203     Opaque<bindings::platform_device>,
204     PhantomData<Ctx>,
205 );
206 
207 impl<Ctx: device::DeviceContext> Device<Ctx> {
208     fn as_raw(&self) -> *mut bindings::platform_device {
209         self.0.get()
210     }
211 }
212 
213 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
214 // argument.
215 kernel::impl_device_context_deref!(unsafe { Device });
216 kernel::impl_device_context_into_aref!(Device);
217 
218 // SAFETY: Instances of `Device` are always reference-counted.
219 unsafe impl crate::types::AlwaysRefCounted for Device {
220     fn inc_ref(&self) {
221         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
222         unsafe { bindings::get_device(self.as_ref().as_raw()) };
223     }
224 
225     unsafe fn dec_ref(obj: NonNull<Self>) {
226         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
227         unsafe { bindings::platform_device_put(obj.cast().as_ptr()) }
228     }
229 }
230 
231 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
232     fn as_ref(&self) -> &device::Device<Ctx> {
233         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
234         // `struct platform_device`.
235         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
236 
237         // SAFETY: `dev` points to a valid `struct device`.
238         unsafe { device::Device::as_ref(dev) }
239     }
240 }
241 
242 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
243     type Error = kernel::error::Error;
244 
245     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
246         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
247         // `struct device`.
248         if !unsafe { bindings::dev_is_platform(dev.as_raw()) } {
249             return Err(EINVAL);
250         }
251 
252         // SAFETY: We've just verified that the bus type of `dev` equals
253         // `bindings::platform_bus_type`, hence `dev` must be embedded in a valid
254         // `struct platform_device` as guaranteed by the corresponding C code.
255         let pdev = unsafe { container_of!(dev.as_raw(), bindings::platform_device, dev) };
256 
257         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
258         Ok(unsafe { &*pdev.cast() })
259     }
260 }
261 
262 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
263 unsafe impl Send for Device {}
264 
265 // SAFETY: `Device` can be shared among threads because all methods of `Device`
266 // (i.e. `Device<Normal>) are thread safe.
267 unsafe impl Sync for Device {}
268