Skip to content

Commit ff65fcf

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 a9b6b51 commit ff65fcf

File tree

6 files changed

+321
-0
lines changed

6 files changed

+321
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18102,6 +18102,7 @@ F: include/asm-generic/pci*
1810218102
F: include/linux/of_pci.h
1810318103
F: include/linux/pci*
1810418104
F: include/uapi/linux/pci*
18105+
F: rust/kernel/pci.rs
1810518106

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

0 commit comments

Comments
 (0)