xref: /linux-6.15/rust/kernel/platform.rs (revision b2e8a832)
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     bindings, container_of, device, driver,
9     error::{to_result, Result},
10     of,
11     prelude::*,
12     str::CStr,
13     types::{ARef, ForeignOwnable, Opaque},
14     ThisModule,
15 };
16 
17 use core::ptr::addr_of_mut;
18 
19 /// An adapter for the registration of platform drivers.
20 pub struct Adapter<T: Driver>(T);
21 
22 impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
23     type RegType = bindings::platform_driver;
24 
25     fn register(
26         pdrv: &Opaque<Self::RegType>,
27         name: &'static CStr,
28         module: &'static ThisModule,
29     ) -> Result {
30         let of_table = match T::OF_ID_TABLE {
31             Some(table) => table.as_ptr(),
32             None => core::ptr::null(),
33         };
34 
35         // SAFETY: It's safe to set the fields of `struct platform_driver` on initialization.
36         unsafe {
37             (*pdrv.get()).driver.name = name.as_char_ptr();
38             (*pdrv.get()).probe = Some(Self::probe_callback);
39             (*pdrv.get()).remove = Some(Self::remove_callback);
40             (*pdrv.get()).driver.of_match_table = of_table;
41         }
42 
43         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
44         to_result(unsafe { bindings::__platform_driver_register(pdrv.get(), module.0) })
45     }
46 
47     fn unregister(pdrv: &Opaque<Self::RegType>) {
48         // SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
49         unsafe { bindings::platform_driver_unregister(pdrv.get()) };
50     }
51 }
52 
53 impl<T: Driver + 'static> Adapter<T> {
54     extern "C" fn probe_callback(pdev: *mut bindings::platform_device) -> kernel::ffi::c_int {
55         // SAFETY: The platform bus only ever calls the probe callback with a valid `pdev`.
56         let dev = unsafe { device::Device::get_device(addr_of_mut!((*pdev).dev)) };
57         // SAFETY: `dev` is guaranteed to be embedded in a valid `struct platform_device` by the
58         // call above.
59         let mut pdev = unsafe { Device::from_dev(dev) };
60 
61         let info = <Self as driver::Adapter>::id_info(pdev.as_ref());
62         match T::probe(&mut pdev, info) {
63             Ok(data) => {
64                 // Let the `struct platform_device` own a reference of the driver's private data.
65                 // SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
66                 // `struct platform_device`.
67                 unsafe { bindings::platform_set_drvdata(pdev.as_raw(), data.into_foreign() as _) };
68             }
69             Err(err) => return Error::to_errno(err),
70         }
71 
72         0
73     }
74 
75     extern "C" fn remove_callback(pdev: *mut bindings::platform_device) {
76         // SAFETY: `pdev` is a valid pointer to a `struct platform_device`.
77         let ptr = unsafe { bindings::platform_get_drvdata(pdev) };
78 
79         // SAFETY: `remove_callback` is only ever called after a successful call to
80         // `probe_callback`, hence it's guaranteed that `ptr` points to a valid and initialized
81         // `KBox<T>` pointer created through `KBox::into_foreign`.
82         let _ = unsafe { KBox::<T>::from_foreign(ptr) };
83     }
84 }
85 
86 impl<T: Driver + 'static> driver::Adapter for Adapter<T> {
87     type IdInfo = T::IdInfo;
88 
89     fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> {
90         T::OF_ID_TABLE
91     }
92 }
93 
94 /// Declares a kernel module that exposes a single platform driver.
95 ///
96 /// # Examples
97 ///
98 /// ```ignore
99 /// kernel::module_platform_driver! {
100 ///     type: MyDriver,
101 ///     name: "Module name",
102 ///     author: "Author name",
103 ///     description: "Description",
104 ///     license: "GPL v2",
105 /// }
106 /// ```
107 #[macro_export]
108 macro_rules! module_platform_driver {
109     ($($f:tt)*) => {
110         $crate::module_driver!(<T>, $crate::platform::Adapter<T>, { $($f)* });
111     };
112 }
113 
114 /// The platform driver trait.
115 ///
116 /// Drivers must implement this trait in order to get a platform driver registered.
117 ///
118 /// # Example
119 ///
120 ///```
121 /// # use kernel::{bindings, c_str, of, platform};
122 ///
123 /// struct MyDriver;
124 ///
125 /// kernel::of_device_table!(
126 ///     OF_TABLE,
127 ///     MODULE_OF_TABLE,
128 ///     <MyDriver as platform::Driver>::IdInfo,
129 ///     [
130 ///         (of::DeviceId::new(c_str!("test,device")), ())
131 ///     ]
132 /// );
133 ///
134 /// impl platform::Driver for MyDriver {
135 ///     type IdInfo = ();
136 ///     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
137 ///
138 ///     fn probe(
139 ///         _pdev: &mut platform::Device,
140 ///         _id_info: Option<&Self::IdInfo>,
141 ///     ) -> Result<Pin<KBox<Self>>> {
142 ///         Err(ENODEV)
143 ///     }
144 /// }
145 ///```
146 pub trait Driver {
147     /// The type holding driver private data about each device id supported by the driver.
148     ///
149     /// TODO: Use associated_type_defaults once stabilized:
150     ///
151     /// type IdInfo: 'static = ();
152     type IdInfo: 'static;
153 
154     /// The table of OF device ids supported by the driver.
155     const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>>;
156 
157     /// Platform driver probe.
158     ///
159     /// Called when a new platform device is added or discovered.
160     /// Implementers should attempt to initialize the device here.
161     fn probe(dev: &mut Device, id_info: Option<&Self::IdInfo>) -> Result<Pin<KBox<Self>>>;
162 }
163 
164 /// The platform device representation.
165 ///
166 /// A platform device is based on an always reference counted `device:Device` instance. Cloning a
167 /// platform device, hence, also increments the base device' reference count.
168 ///
169 /// # Invariants
170 ///
171 /// `Device` holds a valid reference of `ARef<device::Device>` whose underlying `struct device` is a
172 /// member of a `struct platform_device`.
173 #[derive(Clone)]
174 pub struct Device(ARef<device::Device>);
175 
176 impl Device {
177     /// Convert a raw kernel device into a `Device`
178     ///
179     /// # Safety
180     ///
181     /// `dev` must be an `Aref<device::Device>` whose underlying `bindings::device` is a member of a
182     /// `bindings::platform_device`.
183     unsafe fn from_dev(dev: ARef<device::Device>) -> Self {
184         Self(dev)
185     }
186 
187     fn as_raw(&self) -> *mut bindings::platform_device {
188         // SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
189         // embedded in `struct platform_device`.
190         unsafe { container_of!(self.0.as_raw(), bindings::platform_device, dev) }.cast_mut()
191     }
192 }
193 
194 impl AsRef<device::Device> for Device {
195     fn as_ref(&self) -> &device::Device {
196         &self.0
197     }
198 }
199