Skip to content

Commit 683a63b

Browse files
Danilo Krummrichgregkh
authored andcommitted
rust: platform: add basic platform device / driver abstractions
Implement the basic platform bus abstractions required to write a basic platform driver. This includes the following data structures: The `platform::Driver` trait represents the interface to the driver and provides `platform::Driver::probe` for the driver to implement. The `platform::Device` abstraction represents a `struct platform_device`. In order to provide the platform bus specific parts to a generic `driver::Registration` the `driver::RegistrationOps` trait is implemented by `platform::Adapter`. Reviewed-by: Rob Herring (Arm) <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]> Tested-by: Dirk Behme <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Greg Kroah-Hartman <[email protected]>
1 parent 7a718a1 commit 683a63b

File tree

6 files changed

+215
-0
lines changed

6 files changed

+215
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7037,6 +7037,7 @@ F: rust/kernel/device.rs
70377037
F: rust/kernel/device_id.rs
70387038
F: rust/kernel/devres.rs
70397039
F: rust/kernel/driver.rs
7040+
F: rust/kernel/platform.rs
70407041

70417042
DRIVERS FOR OMAP ADAPTIVE VOLTAGE SCALING (AVS)
70427043
M: Nishanth Menon <[email protected]>

rust/bindings/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
#include <linux/pci.h>
2525
#include <linux/phy.h>
2626
#include <linux/pid_namespace.h>
27+
#include <linux/platform_device.h>
2728
#include <linux/poll.h>
2829
#include <linux/refcount.h>
2930
#include <linux/sched.h>

rust/helpers/helpers.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "kunit.c"
2121
#include "mutex.c"
2222
#include "page.c"
23+
#include "platform.c"
2324
#include "pci.c"
2425
#include "pid_namespace.c"
2526
#include "rbtree.c"

rust/helpers/platform.c

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
#include <linux/platform_device.h>
4+
5+
void *rust_helper_platform_get_drvdata(const struct platform_device *pdev)
6+
{
7+
return platform_get_drvdata(pdev);
8+
}
9+
10+
void rust_helper_platform_set_drvdata(struct platform_device *pdev, void *data)
11+
{
12+
platform_set_drvdata(pdev, data);
13+
}

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ pub mod net;
5959
pub mod of;
6060
pub mod page;
6161
pub mod pid_namespace;
62+
pub mod platform;
6263
pub mod prelude;
6364
pub mod print;
6465
pub mod rbtree;

rust/kernel/platform.rs

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
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+
}

0 commit comments

Comments
 (0)