Skip to contentSkip to conversation

rust, nova-core: PCI Class, Vendor support

PATCH Superseded John Hubbard 3 participants 17 messages Aug 22, 2025 – Aug 26, 2025

Subsystems (8)
DRM drivers PCI Rust DRM Rust +4 more subsystems

v6 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v6 cover rust, nova-core: PCI Class, Vendor support

Changes since v5:
* Applied changes from Danilo's review (thanks!):
* Split the nova-core patch into two patches, for nova and pci.
* Added rust/kernel/pci/ to MAINTAINERS.

Changes since v4:
* Applied changes from Danilo's and Alex's review (thanks!):
* Reorganized the patches so that the Nova changes consume the results of Class and Vendor upgrades, all in one shot.

* Made Class and Vendor types get constructed infallibly.

* This was all somewhat disruptive, and also required one more patch in order to properly separate the various steps. But I think it is all correct now. And CLIPPY=1 builds cleanly too.

* Elle Rhumsaa provided a Reviewed-by for v4 (thanks!), but due to the churn in v5 here, I thought it best to not add that tag to v5 yet. Instead, I have directly Cc'd Elle on the patches for now.

Changes since v3:
* Applied changes from Danilo's review (thanks!):

* Moved Class and Vendor to a new pci/id.rs file.
* Added ClassMask, to constrain callers to use only the two valid masks.
* Removed pci_class_code_raw()
* Changed Class and Vendor .as_u32() to .as_raw(), because after Danilo's comment I looked around rust/kernel and learned that .as_raw() is the overwhelmingly used convention.
* Changed vendor_id() to return a Vendor instance directly.
* Also, validated Vendor during construction, just as is done with Class. Both of these items are expected to match known values, even for new devices, so that's a reasonable move.

Changes since v2:

* Applied changes from Danilo's and Alex's review (thanks!):

* Moved everything possible out of the new define_all_pci_classes!() and define_all_pci_vendors!() macros.
* Used "impl TryFrom<u32> for Class/Vendor", instead of .from_u32().
* Made the new DeviceId methods infallible.
* Upgraded DeviceId::from_id() to accept a Vendor struct.

* Changed the names to be a little clearer:
* class_code_raw() --> pci_class_code_raw()
* class_enum() --> pci_class()

* Added doctests for the items that are not yet used in real drivers.

v2 is here:

    https://lore.kernel.org/[email protected]

Changes since v1:

1) Use the pci_device_table for filtering, instead of open-coding filters in the .probe() callback.

2) Add PCI Class (class, subclass, implementation) and PCI Vendor to Rust for Linux.

3) Rebased onto the latest nova-next branch, which is here:
https://gitlab.freedesktop.org/drm/nova.git

v1 is here:

    https://lore.kernel.org/[email protected]
Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>

John Hubbard (5):
rust: pci: provide access to PCI Class and Class-related items
rust: pci: provide access to PCI Vendor values
rust: pci: add DeviceId::from_class_and_vendor() method
gpu: nova-core: avoid probing non-display/compute PCI functions
rust: pci: use pci::Vendor instead of bindings::PCI_VENDOR_ID_*

 MAINTAINERS                           |   1 +
 drivers/gpu/nova-core/driver.rs       |  33 +-
 rust/kernel/pci.rs                    |  46 +-
 rust/kernel/pci/id.rs                 | 591 ++++++++++++++++++++++++++
 samples/rust/rust_dma.rs              |   6 +-
 samples/rust/rust_driver_auxiliary.rs |  12 +-
 samples/rust/rust_driver_pci.rs       |   9 +-
 7 files changed, 670 insertions(+), 28 deletions(-)
 create mode 100644 rust/kernel/pci/id.rs

base-commit: 0dfc23ac2c5b3a62ab27fb9b6ee582b4bb5ce33c

Signature · 1 line
2.50.1
#1 lore raw

PATCH v6 1/5 rust: pci: provide access to PCI Class and Class-related items

Allow callers to write Class::STORAGE_SCSI instead of bindings::PCI_CLASS_STORAGE_SCSI, for example.

New APIs:
Class::STORAGE_SCSI, Class::NETWORK_ETHERNET, etc. Class::as_raw()
Class: From<u32> for Class
ClassMask: Full, ClassSubclass Device::pci_class()

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 MAINTAINERS           |   1 +
 rust/kernel/pci.rs    |  10 ++
 rust/kernel/pci/id.rs | 239 ++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 250 insertions(+)
 create mode 100644 rust/kernel/pci/id.rs
MAINTAINERS +1 -0
index f0d09f7e04e8..4576905a9148 100644
@@ -19532,6 +19532,7 @@ C:	irc://irc.oftc.net/linux-pci
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/pci/pci.git
 F:	rust/helpers/pci.c
 F:	rust/kernel/pci.rs
+F:	rust/kernel/pci/
 F:	samples/rust/rust_driver_pci.rs
 
 PCIE BANDWIDTH CONTROLLER
rust/kernel/pci.rs +10 -0
index 887ee611b553..0faec49bf8a2 100644
@@ -23,6 +23,10 @@
 };
 use kernel::prelude::*;
 
+mod id;
+
+pub use self::id::{Class, ClassMask};
+
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
 
@@ -410,6 +414,12 @@ pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
         Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
     }
+
+    /// Returns the PCI class as a `Class` struct.
+    pub fn pci_class(&self) -> Class {
+        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
+        Class::new(unsafe { (*self.as_raw()).class })
+    }
 }
 
 impl Device<device::Bound> {
rust/kernel/pci/id.rs new file +239 -0

239 lines not on this page · raw message

Signature · 1 line
2.50.1
#2 lore raw

Re: [PATCH v6 1/5] rust: pci: provide access to PCI Class and Class-related items

Hi John,

Quoted 10 lines · John Hubbard

Allow callers to write Class::STORAGE_SCSI instead of bindings::PCI_CLASS_STORAGE_SCSI, for example.

New APIs:
Class::STORAGE_SCSI, Class::NETWORK_ETHERNET, etc. Class::as_raw()
Class: From<u32> for Class
ClassMask: Full, ClassSubclass Device::pci_class()

Quoted 4 lines
Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>

Just one question about the 16 and 24 bit representations below.

<snip>

Quoted 10 lines
rust/kernel/pci/id.rs new file +10 -0
+macro_rules! define_all_pci_classes {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(Self::to_24bit_class($binding));
+            )+

rust/kernel/pci/id.rs line 62

Quoted 10 lines
rust/kernel/pci/id.rs new file +10 -0
+        }
+
+        /// Convert a raw 24-bit class code value to a `Class`.
+        impl From<u32> for Class {
+            fn from(value: u32) -> Self {
+                match value {
+                    $(x if x == Self::$variant.0 => Self::$variant,)+
+                    _ => Self::UNKNOWN,
+                }
+            }

Should we normalize value to 24 bits (i.e. call to_24bit_class) before doing the match? The constants we compare against are all normalized, but if we pass a 16-bit class to this method the result will be UNKNOWN, unless I missed something.

Being able to store a class as either a 16-bit or 24-bit representation in the same type also opens the door to bugs, which we can avoid if we always normalize to 24-bit and make the class/subclass representation accessible through a convenience method only.

rust/kernel/pci/id.rs line 72

Quoted 10 lines
rust/kernel/pci/id.rs new file +10 -0
+        }
+    };
+}
+
+/// Once constructed, a `Class` contains a valid PCI Class code.
+impl Class {
+    /// Create a new Class from a raw 24-bit class code.
+    pub fn new(class_code: u32) -> Self {
+        Self::from(class_code)
+    }

Do we need a new method when the From implementation does exactly the same thing and has the same signature?

#3 lore raw

Re: [PATCH v6 1/5] rust: pci: provide access to PCI Class and Class-related items

Quoted 14 lines · Alexandre Courbot

rust/kernel/pci/id.rs line 62

Quoted 8 lines
rust/kernel/pci/id.rs new file +8 -0
+        /// Convert a raw 24-bit class code value to a `Class`.
+        impl From<u32> for Class {
+            fn from(value: u32) -> Self {
+                match value {
+                    $(x if x == Self::$variant.0 => Self::$variant,)+
+                    _ => Self::UNKNOWN,
+                }
+            }

Should we normalize value to 24 bits (i.e. call to_24bit_class) before doing the match? The constants we compare against are all normalized, but if we pass a 16-bit class to this method the result will be UNKNOWN, unless I missed something.

Quoted 4 lines

Being able to store a class as either a 16-bit or 24-bit representation in the same type also opens the door to bugs, which we can avoid if we always normalize to 24-bit and make the class/subclass representation accessible through a convenience method only.

It's constrained by the PCI ID patterns, and should only be used in order to get values from the C bindings, actually.

Quoted 15 lines

rust/kernel/pci/id.rs line 72

Quoted 11 lines
rust/kernel/pci/id.rs new file +10 -0
+        }
+    };
+}
+
+/// Once constructed, a `Class` contains a valid PCI Class code.
+impl Class {
+    /// Create a new Class from a raw 24-bit class code.
+    pub fn new(class_code: u32) -> Self {
+        Self::from(class_code)
+    }

Do we need a new method when the From implementation does exactly the same thing and has the same signature?

Looks like I'll remove the From, and only provide new, based on the other thread.

thanks,

Signature · 1 line
John Hubbard
#4 lore raw

PATCH v6 2/5 rust: pci: provide access to PCI Vendor values

In reply to John Hubbard

This allows callers to write Vendor::SOME_COMPANY instead of bindings::PCI_VENDOR_ID_SOME_COMPANY.

New APIs:
Vendor::SOME_COMPANY Vendor::as_raw()
Vendor: From<u32> for Vendor

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 rust/kernel/pci.rs    |   2 +-
 rust/kernel/pci/id.rs | 355 +++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 355 insertions(+), 2 deletions(-)
rust/kernel/pci.rs +1 -1
index 0faec49bf8a2..d4675b7d4a86 100644
@@ -25,7 +25,7 @@
 
 mod id;
 
-pub use self::id::{Class, ClassMask};
+pub use self::id::{Class, ClassMask, Vendor};
 
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
rust/kernel/pci/id.rs +354 -1

370 lines not on this page · raw message

Signature · 1 line
2.50.1
#5 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 82 lines · John Hubbard

This allows callers to write Vendor::SOME_COMPANY instead of bindings::PCI_VENDOR_ID_SOME_COMPANY.

New APIs:
Vendor::SOME_COMPANY Vendor::as_raw()
Vendor: From<u32> for Vendor

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 rust/kernel/pci.rs    |   2 +-
 rust/kernel/pci/id.rs | 355 +++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 355 insertions(+), 2 deletions(-)
rust/kernel/pci.rs +1 -1
index 0faec49bf8a2..d4675b7d4a86 100644
@@ -25,7 +25,7 @@
 
 mod id;
 
-pub use self::id::{Class, ClassMask};
+pub use self::id::{Class, ClassMask, Vendor};
 
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
rust/kernel/pci/id.rs +36 -1
index 1291553b4e15..dd91e25a6890 100644
@@ -2,7 +2,7 @@
 
 //! PCI device identifiers and related types.
 //!
-//! This module contains PCI class codes and supporting types.
+//! This module contains PCI class codes, Vendor IDs, and supporting types.
 
 use crate::{bindings, error::code::EINVAL, error::Error, prelude::*};
 use core::fmt;
@@ -115,6 +115,74 @@ fn try_from(value: u32) -> Result<Self, Self::Error> {
     }
 }
 
+/// PCI vendor IDs.
+///
+/// Each entry contains the 16-bit PCI vendor ID as assigned by the PCI SIG.
+///
+/// # Examples
+///
+/// ```
+/// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*};
+/// fn log_device_info(pdev: &pci::Device<Core>) -> Result<()> {
+///     // Get the raw PCI vendor ID and convert to Vendor
+///     let vendor_id = pdev.vendor_id();
+///     let vendor = Vendor::new(vendor_id.into());
+///     dev_info!(
+///         pdev.as_ref(),
+///         "Device: Vendor={}, Device=0x{:x}\n",
+///         vendor,
+///         pdev.device_id()
+///     );
+///     Ok(())
+/// }
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct Vendor(u32);
+
+macro_rules! define_all_pci_vendors {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+
+        impl Vendor {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self($binding as u32);
+            )+

rust/kernel/pci/id.rs fn try_from(value: u32) -> Result<Self, Self::Error> { · line 162

Quoted 10 lines
rust/kernel/pci/id.rs +10 -0
+        }
+
+        /// Convert a raw 16-bit vendor ID to a `Vendor`.
+        impl From<u32> for Vendor {
+            fn from(value: u32) -> Self {
+                match value {
+                    $(x if x == Self::$variant.0 => Self::$variant,)+
+                    _ => Self::UNKNOWN,
+                }
+            }

Naive question from someone with a device tree background and almost no PCI experience: one consequence of using From here is that if I create an non-registered Vendor value (e.g. let vendor = Vendor::from(0xf0f0)), then do vendor.as_raw(), I won't get the value passed initially but the one for UNKNOWN, e.g. 0xffff. Are we ok with this?

rust/kernel/pci/id.rs fn try_from(value: u32) -> Result<Self, Self::Error> { · line 169

Quoted 7 lines
rust/kernel/pci/id.rs +7 -0
+        }
+    };
+}
+
+/// Once constructed, a `Vendor` contains a valid PCI Vendor ID.
+impl Vendor {
+    /// Create a new Vendor from a raw 16-bit vendor ID.

The argument is 32-bit. :) Which triggers the question: why store these as u32 if a u16 is the right size?

maintainer
#6 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 23 lines · Alexandre Courbot
Quoted 23 lines
rust/kernel/pci/id.rs +23 -0
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct Vendor(u32);
+
+macro_rules! define_all_pci_vendors {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+
+        impl Vendor {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self($binding as u32);
+            )+
+        }
+
+        /// Convert a raw 16-bit vendor ID to a `Vendor`.
+        impl From<u32> for Vendor {
+            fn from(value: u32) -> Self {
+                match value {
+                    $(x if x == Self::$variant.0 => Self::$variant,)+
+                    _ => Self::UNKNOWN,
+                }
Quoted 8 lines
Quoted 1 line

+ }

Naive question from someone with a device tree background and almost no PCI experience: one consequence of using From here is that if I create an non-registered Vendor value (e.g. let vendor = Vendor::from(0xf0f0)), then do vendor.as_raw(), I won't get the value passed initially but the one for UNKNOWN, e.g. 0xffff. Are we ok with this?

I think that's fine, since we shouldn't actually hit this. Drivers should only ever use the pre-defined constants of Vendor; consequently the Device::vendor_id() can't return UNKNOWN either.

So, I think the From impl is not ideal, since we can't limit its visibility. In order to improve this, I suggest to use Vendor::new() directly in the macro, and make Vendor::new() private. The same goes for Class, I guess.

#7 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 1 line · Danilo Krummrich

On Mon Aug 25, 2025 at 2:33 PM CEST, Alexandre Courbot wrote:

...

Quoted 3 lines

So, I think the From impl is not ideal, since we can't limit its visibility. In order to improve this, I suggest to use Vendor::new() directly in the macro, and make Vendor::new() private. The same goes for Class, I guess.

OK, will do that.

thanks,

Signature · 1 line
John Hubbard
#8 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

In reply to Danilo Krummrich
Quoted 1 line · Danilo Krummrich

On Mon Aug 25, 2025 at 2:33 PM CEST, Alexandre Courbot wrote:

...

Quoted 7 lines
Quoted 6 lines

Naive question from someone with a device tree background and almost no PCI experience: one consequence of using From here is that if I create an non-registered Vendor value (e.g. let vendor = Vendor::from(0xf0f0)), then do vendor.as_raw(), I won't get the value passed initially but the one for UNKNOWN, e.g. 0xffff. Are we ok with this?

Quoted 7 lines

I think that's fine, since we shouldn't actually hit this. Drivers should only ever use the pre-defined constants of Vendor; consequently the Device::vendor_id() can't return UNKNOWN either.

So, I think the From impl is not ideal, since we can't limit its visibility. In order to improve this, I suggest to use Vendor::new() directly in the macro, and make Vendor::new() private. The same goes for Class, I guess.

Correction: when I went to implement this, I discovered that there is a better way, which addresses both Alex's and your concerns.

The incremental diff below shows how. It provides:

a) .from_raw(), which in this case matches conventions slightly better than new(). (I'm still learning that the Rust way is a bit different that the C++ way! haha).

b) Only the parent module (in this case, that's pci:: ) can call Class::from_raw(). This is exactly what we need. Fully private methods wouldn't work, but leaving it open for any caller to construct a Class item is also a problem.

c) Restored infallible operations, and with it, Alex's request for a reasonable behavior here now works once again:

       from_raw(0x10de).as_raw() == 0x10de
rust/kernel/pci.rs +1 -1
index 0faec49bf8a2..40047a7433b1 100644
@@ -418,7 +418,7 @@ pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
     /// Returns the PCI class as a `Class` struct.
     pub fn pci_class(&self) -> Class {
         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
-        Class::new(unsafe { (*self.as_raw()).class })
+        Class::from_raw(unsafe { (*self.as_raw()).class })
     }
 }
 
rust/kernel/pci/id.rs +4 -14
index 1291553b4e15..399436ffaab9 100644
@@ -51,24 +51,15 @@ impl Class {
                 pub const $variant: Self = Self(Self::to_24bit_class($binding));
             )+
         }
-
-        /// Convert a raw 24-bit class code value to a `Class`.
-        impl From<u32> for Class {
-            fn from(value: u32) -> Self {
-                match value {
-                    $(x if x == Self::$variant.0 => Self::$variant,)+
-                    _ => Self::UNKNOWN,
-                }
-            }
-        }
     };
 }
 
 /// Once constructed, a `Class` contains a valid PCI Class code.
 impl Class {
-    /// Create a new Class from a raw 24-bit class code.
-    pub fn new(class_code: u32) -> Self {
-        Self::from(class_code)
+    /// Create a Class from a raw 24-bit class code.
+    /// Only accessible from the parent pci module.
+    pub(super) fn from_raw(class_code: u32) -> Self {
+        Self(class_code)
     }
 
     /// Get the raw 24-bit class code value.
@@ -235,5 +226,4 @@ fn try_from(value: u32) -> Result<Self, Self::Error> {
     ACCELERATOR_PROCESSING     = bindings::PCI_CLASS_ACCELERATOR_PROCESSING,     // 0x120000
 
     OTHERS                     = bindings::PCI_CLASS_OTHERS,                     // 0xff0000
-    UNKNOWN                    = 0xffffff,
 }

thanks,

Signature · 1 line
John Hubbard
maintainer
#9 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 23 lines · John Hubbard
Quoted 1 line · Danilo Krummrich

On Mon Aug 25, 2025 at 2:33 PM CEST, Alexandre Courbot wrote:

...

Quoted 7 lines
Quoted 6 lines

Naive question from someone with a device tree background and almost no PCI experience: one consequence of using From here is that if I create an non-registered Vendor value (e.g. let vendor = Vendor::from(0xf0f0)), then do vendor.as_raw(), I won't get the value passed initially but the one for UNKNOWN, e.g. 0xffff. Are we ok with this?

Quoted 7 lines

I think that's fine, since we shouldn't actually hit this. Drivers should only ever use the pre-defined constants of Vendor; consequently the Device::vendor_id() can't return UNKNOWN either.

So, I think the From impl is not ideal, since we can't limit its visibility. In order to improve this, I suggest to use Vendor::new() directly in the macro, and make Vendor::new() private. The same goes for Class, I guess.

Correction: when I went to implement this, I discovered that there is a better way, which addresses both Alex's and your concerns.

The incremental diff below shows how. It provides:

Quoted 8 lines

a) .from_raw(), which in this case matches conventions slightly better than new(). (I'm still learning that the Rust way is a bit different that the C++ way! haha).

b) Only the parent module (in this case, that's pci:: ) can call Class::from_raw(). This is exactly what we need. Fully private methods wouldn't work, but leaving it open for any caller to construct a Class item is also a problem.

Sorry, that's on me being not precise. When I said private I meant private to the parent module.

The diff looks good, thanks!

Please also make sure to add #[inline] where appropriate and rebase onto driver-core-next.

#10 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 8 lines · Danilo Krummrich
Quoted 3 lines · John Hubbard
Quoted 1 line · Danilo Krummrich

On Mon Aug 25, 2025 at 2:33 PM CEST, Alexandre Courbot wrote:

...

Sorry, that's on me being not precise. When I said private I meant private to the parent module.

The diff looks good, thanks!

Huge relief! :)

Quoted 3 lines

Please also make sure to add #[inline] where appropriate and rebase onto driver-core-next.

I have no idea "where appropriate" is, here. These are not hot paths, and the existing pci.rs methods such as Device::vendor_id() are not inlined, and so my initial approach is to just not inline any of this...

thanks,

Signature · 1 line
John Hubbard
maintainer
#11 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 3 lines · John Hubbard

I have no idea "where appropriate" is, here. These are not hot paths, and the existing pci.rs methods such as Device::vendor_id() are not inlined, and so my initial approach is to just not inline any of this...

I think we can inline those functions that only consist out of a single constructor (i.e. Self {...}) or a single function call either way.

#12 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

Quoted 7 lines · Danilo Krummrich
Quoted 3 lines · John Hubbard

I have no idea "where appropriate" is, here. These are not hot paths, and the existing pci.rs methods such as Device::vendor_id() are not inlined, and so my initial approach is to just not inline any of this...

I think we can inline those functions that only consist out of a single constructor (i.e. Self {...}) or a single function call either way.

Got it, thanks for clarifying!

thanks,

Signature · 1 line
John Hubbard
#13 lore raw

Re: [PATCH v6 2/5] rust: pci: provide access to PCI Vendor values

In reply to Alexandre Courbot
Quoted 6 lines · Alexandre Courbot

rust/kernel/pci/id.rs fn try_from(value: u32) -> Result<Self, Self::Error> { · line 169

Quoted 3 lines
rust/kernel/pci/id.rs +3 -0
+/// Once constructed, a `Vendor` contains a valid PCI Vendor ID.
+impl Vendor {
+    /// Create a new Vendor from a raw 16-bit vendor ID.

The argument is 32-bit. :) Which triggers the question: why store these as u32 if a u16 is the right size?

Good point! I'll change it to u16.

thanks,

Signature · 1 line
John Hubbard
#14 lore raw

PATCH v6 3/5 rust: pci: add DeviceId::from_class_and_vendor() method

In reply to John Hubbard

Add a new method to create PCI DeviceIds that match both a specific vendor and PCI class. This is more targeted than the existing from_class() method as it filters on both vendor and class criteria.

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 rust/kernel/pci.rs | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)
rust/kernel/pci.rs +21 -0
index d4675b7d4a86..504593c882c9 100644
@@ -161,6 +161,27 @@ pub const fn from_class(class: u32, class_mask: u32) -> Self {
             override_only: 0,
         })
     }
+
+    /// Create a new `pci::DeviceId` from a class number, mask, and specific vendor.
+    ///
+    /// This is more targeted than [`DeviceId::from_class`]: in addition to matching by Vendor, it
+    /// also matches the PCI Class (up to the entire 24 bits, depending on the mask).
+    pub const fn from_class_and_vendor(
+        class: Class,
+        class_mask: ClassMask,
+        vendor: Vendor,
+    ) -> Self {
+        Self(bindings::pci_device_id {
+            vendor: vendor.as_raw(),
+            device: DeviceId::PCI_ANY_ID,
+            subvendor: DeviceId::PCI_ANY_ID,
+            subdevice: DeviceId::PCI_ANY_ID,
+            class: class.as_raw(),
+            class_mask: class_mask.as_raw(),
+            driver_data: 0,
+            override_only: 0,
+        })
+    }
 }
 
 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id` and does not add
Signature · 1 line
2.50.1
#15 lore raw

PATCH v6 4/5 gpu: nova-core: avoid probing non-display/compute PCI functions

In reply to John Hubbard

NovaCore has so far been too imprecise about figuring out if .probe() has found a supported PCI PF (Physical Function). By that I mean:
.probe() sets up BAR0 (which involves a lot of very careful devres and Device<Bound> details behind the scenes). And then if it is dealing with a non-supported device such as the .1 audio PF on many GPUs, it fails out due to an unexpected BAR0 size. We have been fortunate that the BAR0 sizes are different.

Really, we should be filtering on PCI class ID instead. These days I think we can confidently pick out Nova's supported PF's via PCI class ID. And if not, then we'll revisit.

The approach here is to filter on "Display VGA" or "Display 3D", which is how PCI class IDs express "this is a modern GPU's PF".

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 drivers/gpu/nova-core/driver.rs | 33 ++++++++++++++++++++++++++++-----
 1 file changed, 28 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/driver.rs +28 -5
index 274989ea1fb4..5d23a91f51dd 100644
@@ -1,6 +1,14 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::{auxiliary, bindings, c_str, device::Core, pci, prelude::*, sizes::SZ_16M, sync::Arc};
+use kernel::{
+    auxiliary, c_str,
+    device::Core,
+    pci,
+    pci::{Class, ClassMask, Vendor},
+    prelude::*,
+    sizes::SZ_16M,
+    sync::Arc,
+};
 
 use crate::gpu::Gpu;
 
@@ -18,10 +26,25 @@ pub(crate) struct NovaCore {
     PCI_TABLE,
     MODULE_PCI_TABLE,
     <NovaCore as pci::Driver>::IdInfo,
-    [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_NVIDIA, bindings::PCI_ANY_ID as u32),
-        ()
-    )]
+    [
+        // Modern NVIDIA GPUs will show up as either VGA or 3D controllers.
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_VGA,
+                ClassMask::ClassSubclass,
+                Vendor::NVIDIA
+            ),
+            ()
+        ),
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_3D,
+                ClassMask::ClassSubclass,
+                Vendor::NVIDIA
+            ),
+            ()
+        ),
+    ]
 );
 
 impl pci::Driver for NovaCore {
Signature · 1 line
2.50.1
#16 lore raw

PATCH v6 5/5 rust: pci: use pci::Vendor instead of bindings::PCI_VENDOR_ID_*

In reply to John Hubbard

Change Device::vendor_id() to return a Vendor type, and change DeviceId::from_id() to accept a Vendor type.

Use the new pci::Vendor in the various Rust for Linux callers who were previously using bindings::PCI_VENDOR_ID_*.

Doing so also allows removing "use kernel::bindings" entirely from most of the affected files here.

Cc Danilo Krummrich <[email protected]>
Cc Alexandre Courbot <[email protected]>
Cc Elle Rhumsaa <[email protected]>
---
 rust/kernel/pci.rs                    | 15 ++++++++-------
 rust/kernel/pci/id.rs                 |  5 ++---
 samples/rust/rust_dma.rs              |  6 +-----
 samples/rust/rust_driver_auxiliary.rs | 12 +++++-------
 samples/rust/rust_driver_pci.rs       |  9 +++++----
 5 files changed, 21 insertions(+), 26 deletions(-)
rust/kernel/pci.rs +8 -7
index 504593c882c9..0ef8754f83e5 100644
@@ -132,10 +132,10 @@ impl DeviceId {
 
     /// Equivalent to C's `PCI_DEVICE` macro.
     ///
-    /// Create a new `pci::DeviceId` from a vendor and device ID number.
-    pub const fn from_id(vendor: u32, device: u32) -> Self {
+    /// Create a new `pci::DeviceId` from a vendor and device ID.
+    pub const fn from_id(vendor: Vendor, device: u32) -> Self {
         Self(bindings::pci_device_id {
-            vendor,
+            vendor: vendor.as_raw(),
             device,
             subvendor: DeviceId::PCI_ANY_ID,
             subdevice: DeviceId::PCI_ANY_ID,
@@ -231,7 +231,7 @@ macro_rules! pci_device_table {
 ///     <MyDriver as pci::Driver>::IdInfo,
 ///     [
 ///         (
-///             pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32),
+///             pci::DeviceId::from_id(pci::Vendor::REDHAT, bindings::PCI_ANY_ID as u32),
 ///             (),
 ///         )
 ///     ]
@@ -412,10 +412,11 @@ fn as_raw(&self) -> *mut bindings::pci_dev {
 }
 
 impl Device {
-    /// Returns the PCI vendor ID.
-    pub fn vendor_id(&self) -> u16 {
+    /// Returns the PCI vendor ID as a validated Vendor.
+    pub fn vendor_id(&self) -> Vendor {
         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
-        unsafe { (*self.as_raw()).vendor }
+        let vendor_id = unsafe { (*self.as_raw()).vendor };
+        Vendor::new(u32::from(vendor_id))
     }
 
     /// Returns the PCI device ID.
rust/kernel/pci/id.rs +2 -3
index dd91e25a6890..2e4c7edc48a4 100644
@@ -124,9 +124,8 @@ fn try_from(value: u32) -> Result<Self, Self::Error> {
 /// ```
 /// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*};
 /// fn log_device_info(pdev: &pci::Device<Core>) -> Result<()> {
-///     // Get the raw PCI vendor ID and convert to Vendor
-///     let vendor_id = pdev.vendor_id();
-///     let vendor = Vendor::new(vendor_id.into());
+///     // Get the validated PCI vendor ID
+///     let vendor = pdev.vendor_id();
 ///     dev_info!(
 ///         pdev.as_ref(),
 ///         "Device: Vendor={}, Device=0x{:x}\n",
samples/rust/rust_dma.rs +1 -5
index c5e7cce68654..f3385c4a7e5b 100644
@@ -5,7 +5,6 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    bindings,
     device::Core,
     dma::{CoherentAllocation, Device, DmaMask},
     pci,
@@ -45,10 +44,7 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}
     PCI_TABLE,
     MODULE_PCI_TABLE,
     <DmaSampleDriver as pci::Driver>::IdInfo,
-    [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
-        ()
-    )]
+    [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
 impl pci::Driver for DmaSampleDriver {
samples/rust/rust_driver_auxiliary.rs +5 -7
index f2a820683fc3..55ece336ee45 100644
@@ -5,7 +5,7 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    auxiliary, bindings, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
+    auxiliary, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
 };
 
 use pin_init::PinInit;
@@ -50,10 +50,7 @@ struct ParentDriver {
     PCI_TABLE,
     MODULE_PCI_TABLE,
     <ParentDriver as pci::Driver>::IdInfo,
-    [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
-        ()
-    )]
+    [(pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5), ())]
 );
 
 impl pci::Driver for ParentDriver {
@@ -81,11 +78,12 @@ fn connect(adev: &auxiliary::Device) -> Result<()> {
         let parent = adev.parent().ok_or(EINVAL)?;
         let pdev: &pci::Device = parent.try_into()?;
 
+        let vendor = pdev.vendor_id();
         dev_info!(
             adev.as_ref(),
-            "Connect auxiliary {} with parent: VendorID={:#x}, DeviceID={:#x}\n",
+            "Connect auxiliary {} with parent: VendorID={}, DeviceID={:#x}\n",
             adev.id(),
-            pdev.vendor_id(),
+            vendor,
             pdev.device_id()
         );
 
samples/rust/rust_driver_pci.rs +5 -4
index 606946ff4d7f..f3819ac4bad6 100644
@@ -4,7 +4,7 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
-use kernel::{bindings, c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
+use kernel::{c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
 
 struct Regs;
 
@@ -38,7 +38,7 @@ struct SampleDriver {
     MODULE_PCI_TABLE,
     <SampleDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT, 0x5),
         TestIndex::NO_EVENTFD
     )]
 );
@@ -66,10 +66,11 @@ impl pci::Driver for SampleDriver {
     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
 
     fn probe(pdev: &pci::Device<Core>, info: &Self::IdInfo) -> Result<Pin<KBox<Self>>> {
+        let vendor = pdev.vendor_id();
         dev_dbg!(
             pdev.as_ref(),
-            "Probe Rust PCI driver sample (PCI ID: 0x{:x}, 0x{:x}).\n",
-            pdev.vendor_id(),
+            "Probe Rust PCI driver sample (PCI ID: {}, 0x{:x}).\n",
+            vendor,
             pdev.device_id()
         );
 
Signature · 1 line
2.50.1