Skip to content

Commit 9490ecf

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 <[email protected]> Signed-off-by: FUJITA Tomonori <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]>
1 parent d3fb98b commit 9490ecf

File tree

6 files changed

+307
-0
lines changed

6 files changed

+307
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18099,6 +18099,7 @@ F: include/asm-generic/pci*
1809918099
F: include/linux/of_pci.h
1810018100
F: include/linux/pci*
1810118101
F: include/uapi/linux/pci*
18102+
F: rust/kernel/pci.rs
1810218103

1810318104
PCIE BANDWIDTH CONTROLLER
1810418105
M: Ilpo Järvinen <[email protected]>

rust/bindings/bindings_helper.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include <linux/jump_label.h>
2121
#include <linux/mdio.h>
2222
#include <linux/miscdevice.h>
23+
#include <linux/pci.h>
2324
#include <linux/phy.h>
2425
#include <linux/pid_namespace.h>
2526
#include <linux/poll.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 "pci.c"
2324
#include "pid_namespace.c"
2425
#include "rbtree.c"
2526
#include "rcu.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+
resource_size_t 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
@@ -82,6 +82,8 @@ pub mod workqueue;
8282
pub use bindings;
8383
pub mod io;
8484
pub use macros;
85+
#[cfg(all(CONFIG_PCI, CONFIG_PCI_MSI))]
86+
pub mod pci;
8587
pub use uapi;
8688

8789
#[doc(hidden)]

rust/kernel/pci.rs

Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Abstractions for the PCI bus.
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 bus only ever calls the probe callback with a valid pointer to a
53+
// `struct pci_dev`.
54+
let dev = unsafe { device::Device::get_device(&mut (*pdev).dev) };
55+
// SAFETY: `dev` is guaranteed to be embedded in a valid `struct pci_dev` by the call
56+
// above.
57+
let mut pdev = unsafe { Device::from_dev(dev) };
58+
59+
// SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct pci_device_id` and
60+
// does not add additional invariants, so it's safe to transmute.
61+
let id = unsafe { &*id.cast::<DeviceId>() };
62+
let info = T::ID_TABLE.info(id.index());
63+
64+
match T::probe(&mut pdev, id, info) {
65+
Ok(data) => {
66+
// Let the `struct pci_dev` own a reference of the driver's private data.
67+
// SAFETY: By the type invariant `pdev.as_raw` returns a valid pointer to a
68+
// `struct pci_dev`.
69+
unsafe { bindings::pci_set_drvdata(pdev.as_raw(), data.into_foreign() as _) };
70+
}
71+
Err(err) => return Error::to_errno(err),
72+
}
73+
74+
0
75+
}
76+
77+
extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
78+
// SAFETY: The PCI bus only ever calls the remove callback with a valid pointer to a
79+
// `struct pci_dev`.
80+
let ptr = unsafe { bindings::pci_get_drvdata(pdev) };
81+
82+
// SAFETY: `remove_callback` is only ever called after a successful call to
83+
// `probe_callback`, hence it's guaranteed that `ptr` points to a valid and initialized
84+
// `KBox<T>` pointer created through `KBox::into_foreign`.
85+
let _ = unsafe { KBox::<T>::from_foreign(ptr) };
86+
}
87+
}
88+
89+
/// Declares a kernel module that exposes a single PCI driver.
90+
///
91+
/// # Example
92+
///
93+
///```ignore
94+
/// kernel::module_pci_driver! {
95+
/// type: MyDriver,
96+
/// name: "Module name",
97+
/// author: "Author name",
98+
/// description: "Description",
99+
/// license: "GPL v2",
100+
/// }
101+
///```
102+
#[macro_export]
103+
macro_rules! module_pci_driver {
104+
($($f:tt)*) => {
105+
$crate::module_driver!(<T>, $crate::pci::Adapter<T>, { $($f)* });
106+
};
107+
}
108+
109+
/// Abstraction for bindings::pci_device_id.
110+
#[repr(transparent)]
111+
#[derive(Clone, Copy)]
112+
pub struct DeviceId(bindings::pci_device_id);
113+
114+
impl DeviceId {
115+
const PCI_ANY_ID: u32 = !0;
116+
117+
/// PCI_DEVICE macro.
118+
pub const fn new(vendor: u32, device: u32) -> Self {
119+
Self(bindings::pci_device_id {
120+
vendor,
121+
device,
122+
subvendor: DeviceId::PCI_ANY_ID,
123+
subdevice: DeviceId::PCI_ANY_ID,
124+
class: 0,
125+
class_mask: 0,
126+
driver_data: 0,
127+
override_only: 0,
128+
})
129+
}
130+
131+
/// PCI_DEVICE_CLASS macro.
132+
pub const fn with_class(class: u32, class_mask: u32) -> Self {
133+
Self(bindings::pci_device_id {
134+
vendor: DeviceId::PCI_ANY_ID,
135+
device: DeviceId::PCI_ANY_ID,
136+
subvendor: DeviceId::PCI_ANY_ID,
137+
subdevice: DeviceId::PCI_ANY_ID,
138+
class,
139+
class_mask,
140+
driver_data: 0,
141+
override_only: 0,
142+
})
143+
}
144+
}
145+
146+
// Allow drivers R/O access to the fields of `pci_device_id`; should we prefer accessor functions
147+
// to void exposing C structure fields?
148+
impl Deref for DeviceId {
149+
type Target = bindings::pci_device_id;
150+
151+
fn deref(&self) -> &Self::Target {
152+
&self.0
153+
}
154+
}
155+
156+
// SAFETY:
157+
// * `DeviceId` is a `#[repr(transparent)` wrapper of `pci_device_id` and does not add
158+
// additional invariants, so it's safe to transmute to `RawType`.
159+
// * `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
160+
unsafe impl RawDeviceId for DeviceId {
161+
type RawType = bindings::pci_device_id;
162+
163+
const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data);
164+
165+
fn index(&self) -> usize {
166+
self.driver_data as _
167+
}
168+
}
169+
170+
/// IdTable type for PCI
171+
pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
172+
173+
/// Create a PCI `IdTable` with its alias for modpost.
174+
#[macro_export]
175+
macro_rules! pci_device_table {
176+
($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
177+
const $table_name: $crate::device_id::IdArray<
178+
$crate::pci::DeviceId,
179+
$id_info_type,
180+
{ $table_data.len() },
181+
> = $crate::device_id::IdArray::new($table_data);
182+
183+
$crate::module_device_table!("pci", $module_table_name, $table_name);
184+
};
185+
}
186+
187+
/// The PCI driver trait.
188+
///
189+
/// # Example
190+
///
191+
///```
192+
/// # use kernel::{bindings, pci};
193+
///
194+
/// struct MyDriver;
195+
///
196+
/// kernel::pci_device_table!(
197+
/// PCI_TABLE,
198+
/// MODULE_PCI_TABLE,
199+
/// <MyDriver as pci::Driver>::IdInfo,
200+
/// [
201+
/// (pci::DeviceId::new(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32), ())
202+
/// ]
203+
/// );
204+
///
205+
/// impl pci::Driver for MyDriver {
206+
/// type IdInfo = ();
207+
/// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
208+
///
209+
/// fn probe(
210+
/// _pdev: &mut pci::Device,
211+
/// _id: &pci::DeviceId,
212+
/// _id_info: &Self::IdInfo,
213+
/// ) -> Result<Pin<KBox<Self>>> {
214+
/// Err(ENODEV)
215+
/// }
216+
/// }
217+
///```
218+
/// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the
219+
/// `Adapter` documentation for an example.
220+
pub trait Driver {
221+
/// The type holding information about each device id supported by the driver.
222+
///
223+
/// TODO: Use associated_type_defaults once stabilized:
224+
///
225+
/// type IdInfo: 'static = ();
226+
type IdInfo: 'static;
227+
228+
/// The table of device ids supported by the driver.
229+
const ID_TABLE: IdTable<Self::IdInfo>;
230+
231+
/// PCI driver probe.
232+
///
233+
/// Called when a new platform device is added or discovered.
234+
/// Implementers should attempt to initialize the device here.
235+
fn probe(dev: &mut Device, id: &DeviceId, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>;
236+
}
237+
238+
/// The PCI device representation.
239+
///
240+
/// A PCI device is based on an always reference counted `device:Device` instance. Cloning a PCI
241+
/// device, hence, also increments the base device' reference count.
242+
#[derive(Clone)]
243+
pub struct Device(ARef<device::Device>);
244+
245+
impl Device {
246+
/// Create a PCI Device instance from an existing `device::Device`.
247+
///
248+
/// # Safety
249+
///
250+
/// `dev` must be an `ARef<device::Device>` whose underlying `bindings::device` is a member of
251+
/// a `bindings::pci_dev`.
252+
pub unsafe fn from_dev(dev: ARef<device::Device>) -> Self {
253+
Self(dev)
254+
}
255+
256+
fn as_raw(&self) -> *mut bindings::pci_dev {
257+
// SAFETY: By the type invariant `self.0.as_raw` is a pointer to the `struct device`
258+
// embedded in `struct pci_dev`.
259+
unsafe { container_of!(self.0.as_raw(), bindings::pci_dev, dev) as _ }
260+
}
261+
262+
/// Enable memory resources for this device.
263+
pub fn enable_device_mem(&self) -> Result {
264+
// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
265+
let ret = unsafe { bindings::pci_enable_device_mem(self.as_raw()) };
266+
if ret != 0 {
267+
Err(Error::from_errno(ret))
268+
} else {
269+
Ok(())
270+
}
271+
}
272+
273+
/// Enable bus-mastering for this device.
274+
pub fn set_master(&self) {
275+
// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
276+
unsafe { bindings::pci_set_master(self.as_raw()) };
277+
}
278+
}
279+
280+
impl AsRef<device::Device> for Device {
281+
fn as_ref(&self) -> &device::Device {
282+
&self.0
283+
}
284+
}

0 commit comments

Comments
 (0)