Skip to content

Commit f06e61d

Browse files
author
Danilo Krummrich
committed
rust: pci: add basic PCI device / driver abstractions
Implement the basic PCI abstractions required to write a basic PCI driver. This includes the following data structures: The `pci::Driver` trait represents the interface to the driver and provides `pci::Driver::probe` for the driver to implement. The `pci::Device` abstraction represents a `struct pci_dev` and provides abstractions for common functions, such as `pci::Device::set_master`. In order to provide the PCI specific parts to a generic `driver::Registration` the `driver::RegistrationOps` trait is implemented by `pci::Adapter`. `pci::DeviceId` implements PCI device IDs based on the generic `device_id::RawDevceId` abstraction. Co-developed-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Signed-off-by: Danilo Krummrich <dakr@kernel.org>
1 parent 5abe57e commit f06e61d

File tree

5 files changed

+288
-0
lines changed

5 files changed

+288
-0
lines changed

rust/bindings/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <linux/firmware.h>
1616
#include <linux/jiffies.h>
1717
#include <linux/mdio.h>
18+
#include <linux/pci.h>
1819
#include <linux/phy.h>
1920
#include <linux/refcount.h>
2021
#include <linux/sched.h>

rust/helpers/helpers.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include "kunit.c"
1818
#include "mutex.c"
1919
#include "page.c"
20+
#include "pci.c"
2021
#include "rbtree.c"
2122
#include "rcu.c"
2223
#include "refcount.c"

rust/helpers/pci.c

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
#include <linux/pci.h>
4+
5+
void rust_helper_pci_set_drvdata(struct pci_dev *pdev, void *data)
6+
{
7+
pci_set_drvdata(pdev, data);
8+
}
9+
10+
void *rust_helper_pci_get_drvdata(struct pci_dev *pdev)
11+
{
12+
return pci_get_drvdata(pdev);
13+
}
14+
15+
u64 rust_helper_pci_resource_len(struct pci_dev *pdev, int bar)
16+
{
17+
return pci_resource_len(pdev, bar);
18+
}

rust/kernel/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ pub mod workqueue;
7373
pub use bindings;
7474
pub mod io;
7575
pub use macros;
76+
#[cfg(all(CONFIG_PCI, CONFIG_PCI_MSI))]
77+
pub mod pci;
7678
pub use uapi;
7779

7880
#[doc(hidden)]

rust/kernel/pci.rs

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Wrappers for the PCI subsystem
4+
//!
5+
//! C header: [`include/linux/pci.h`](srctree/include/linux/pci.h)
6+
7+
use crate::{
8+
bindings, container_of, device,
9+
device_id::RawDeviceId,
10+
driver,
11+
error::{to_result, Result},
12+
str::CStr,
13+
types::{ARef, ForeignOwnable},
14+
ThisModule,
15+
};
16+
use core::ops::Deref;
17+
use kernel::prelude::*;
18+
19+
/// An adapter for the registration of PCI drivers.
20+
pub struct Adapter<T: Driver>(T);
21+
22+
impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> {
23+
type RegType = bindings::pci_driver;
24+
25+
fn register(
26+
pdrv: &mut Self::RegType,
27+
name: &'static CStr,
28+
module: &'static ThisModule,
29+
) -> Result {
30+
pdrv.name = name.as_char_ptr();
31+
pdrv.probe = Some(Self::probe_callback);
32+
pdrv.remove = Some(Self::remove_callback);
33+
pdrv.id_table = T::ID_TABLE.as_ptr();
34+
35+
// SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
36+
to_result(unsafe {
37+
bindings::__pci_register_driver(pdrv as _, module.0, name.as_char_ptr())
38+
})
39+
}
40+
41+
fn unregister(pdrv: &mut Self::RegType) {
42+
// SAFETY: `pdrv` is guaranteed to be a valid `RegType`.
43+
unsafe { bindings::pci_unregister_driver(pdrv) }
44+
}
45+
}
46+
47+
impl<T: Driver + 'static> Adapter<T> {
48+
extern "C" fn probe_callback(
49+
pdev: *mut bindings::pci_dev,
50+
id: *const bindings::pci_device_id,
51+
) -> core::ffi::c_int {
52+
// SAFETY: The PCI core only ever calls the probe callback with a valid `pdev`.
53+
let dev = unsafe { device::Device::from_raw(&mut (*pdev).dev) };
54+
// SAFETY: `dev` is guaranteed to be embedded in a valid `struct pci_dev` by the call
55+
// above.
56+
let mut pdev = unsafe { Device::from_dev(dev) };
57+
58+
// SAFETY: The PCI core only ever calls the probe callback with a valid `id`.
59+
let index = unsafe { (*id).driver_data };
60+
let raw_id = T::ID_TABLE.id(index as _);
61+
62+
// SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `DeviceId::RawType` and does not
63+
// add additional invariants, so it's safe to transmute to `DeviceId`.
64+
let id = unsafe {
65+
core::mem::transmute::<&<DeviceId as RawDeviceId>::RawType, &DeviceId>(raw_id)
66+
};
67+
let info = T::ID_TABLE.info(index as _);
68+
69+
match T::probe(&mut pdev, id, info) {
70+
Ok(data) => {
71+
// Let the `struct pci_dev` own a reference of the driver's private data.
72+
// SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
73+
// `struct pci_dev`.
74+
unsafe { bindings::pci_set_drvdata(pdev.as_raw(), data.into_foreign() as _) };
75+
}
76+
Err(err) => return Error::to_errno(err),
77+
}
78+
79+
0
80+
}
81+
82+
extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
83+
// SAFETY: The PCI core only ever calls the remove callback with a valid `pdev`. `ptr`
84+
// points to a valid reference of the driver's private data; it was set by
85+
// `Adapter::probe_callback`.
86+
let _ = unsafe {
87+
let ptr = bindings::pci_get_drvdata(pdev);
88+
89+
KBox::<T>::from_foreign(ptr)
90+
};
91+
}
92+
}
93+
94+
/// Declares a kernel module that exposes a single PCI driver.
95+
///
96+
/// # Example
97+
///
98+
///```ignore
99+
/// kernel::module_pci_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_pci_driver {
109+
($($f:tt)*) => {
110+
$crate::module_driver!(<T>, $crate::pci::Adapter<T>, { $($f)* });
111+
};
112+
}
113+
114+
/// Abstraction for bindings::pci_device_id.
115+
#[repr(transparent)]
116+
#[derive(Clone, Copy)]
117+
pub struct DeviceId(bindings::pci_device_id);
118+
119+
impl DeviceId {
120+
const PCI_ANY_ID: u32 = !0;
121+
122+
/// PCI_DEVICE macro.
123+
pub const fn new(vendor: u32, device: u32) -> Self {
124+
Self(bindings::pci_device_id {
125+
vendor,
126+
device,
127+
subvendor: DeviceId::PCI_ANY_ID,
128+
subdevice: DeviceId::PCI_ANY_ID,
129+
class: 0,
130+
class_mask: 0,
131+
driver_data: 0,
132+
override_only: 0,
133+
})
134+
}
135+
136+
/// PCI_DEVICE_CLASS macro.
137+
pub const fn with_class(class: u32, class_mask: u32) -> Self {
138+
Self(bindings::pci_device_id {
139+
vendor: DeviceId::PCI_ANY_ID,
140+
device: DeviceId::PCI_ANY_ID,
141+
subvendor: DeviceId::PCI_ANY_ID,
142+
subdevice: DeviceId::PCI_ANY_ID,
143+
class,
144+
class_mask,
145+
driver_data: 0,
146+
override_only: 0,
147+
})
148+
}
149+
}
150+
151+
// Allow drivers R/O access to the fields of `pci_device_id`; should we prefer accessor functions
152+
// to void exposing C structure fields?
153+
impl Deref for DeviceId {
154+
type Target = bindings::pci_device_id;
155+
156+
fn deref(&self) -> &Self::Target {
157+
&self.0
158+
}
159+
}
160+
161+
// SAFETY:
162+
// * `DeviceId` is a `#[repr(transparent)` wrapper of `pci_device_id` and does not add
163+
// additional invariants, so it's safe to transmute to `RawType`.
164+
// * `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
165+
unsafe impl RawDeviceId for DeviceId {
166+
type RawType = bindings::pci_device_id;
167+
168+
const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data);
169+
}
170+
171+
/// IdTable type for PCI
172+
pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
173+
174+
/// The PCI driver trait.
175+
///
176+
/// # Example
177+
///
178+
///```
179+
/// # use kernel::{bindings, device_id::IdArray, pci, sync::Arc};
180+
///
181+
/// struct MyDriver;
182+
/// struct MyDeviceData;
183+
///
184+
/// impl pci::Driver for MyDriver {
185+
/// type IdInfo = ();
186+
///
187+
/// const ID_TABLE: pci::IdTable<Self::IdInfo> = &IdArray::new([
188+
/// (pci::DeviceId::new(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32), ())
189+
/// ]);
190+
///
191+
/// fn probe(
192+
/// _pdev: &mut pci::Device,
193+
/// _id: &pci::DeviceId,
194+
/// _id_info: &Self::IdInfo,
195+
/// ) -> Result<Pin<KBox<Self>>> {
196+
/// Err(ENODEV)
197+
/// }
198+
/// }
199+
///```
200+
/// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the
201+
/// `Adapter` documentation for an example.
202+
pub trait Driver {
203+
/// The type holding information about each device id supported by the driver.
204+
///
205+
/// TODO: Use associated_type_defaults once stabilized:
206+
///
207+
/// type IdInfo: 'static = ();
208+
type IdInfo: 'static;
209+
210+
/// The table of device ids supported by the driver.
211+
const ID_TABLE: IdTable<Self::IdInfo>;
212+
213+
/// PCI driver probe.
214+
///
215+
/// Called when a new platform device is added or discovered.
216+
/// Implementers should attempt to initialize the device here.
217+
fn probe(dev: &mut Device, id: &DeviceId, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>;
218+
}
219+
220+
/// The PCI device representation.
221+
///
222+
/// A PCI device is based on an always reference counted `device:Device` instance. Cloning a PCI
223+
/// device, hence, also increments the base device' reference count.
224+
#[derive(Clone)]
225+
pub struct Device(ARef<device::Device>);
226+
227+
impl Device {
228+
/// Create a PCI Device instance from an existing `device::Device`.
229+
///
230+
/// # Safety
231+
///
232+
/// `dev` must be an `ARef<device::Device>` whose underlying `bindings::device` is a member of
233+
/// a `bindings::pci_dev`.
234+
pub unsafe fn from_dev(dev: ARef<device::Device>) -> Self {
235+
Self(dev)
236+
}
237+
238+
fn as_raw(&self) -> *mut bindings::pci_dev {
239+
// SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
240+
// embedded in `struct pci_dev`.
241+
unsafe { container_of!(self.0.as_raw(), bindings::pci_dev, dev) as _ }
242+
}
243+
244+
/// Enable memory resources for this device.
245+
pub fn enable_device_mem(&self) -> Result {
246+
// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
247+
let ret = unsafe { bindings::pci_enable_device_mem(self.as_raw()) };
248+
if ret != 0 {
249+
Err(Error::from_errno(ret))
250+
} else {
251+
Ok(())
252+
}
253+
}
254+
255+
/// Enable bus-mastering for this device.
256+
pub fn set_master(&self) {
257+
// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
258+
unsafe { bindings::pci_set_master(self.as_raw()) };
259+
}
260+
}
261+
262+
impl AsRef<device::Device> for Device {
263+
fn as_ref(&self) -> &device::Device {
264+
&self.0
265+
}
266+
}

0 commit comments

Comments
 (0)